【问题标题】:how to use java onclick shuffle array如何使用java onclick shuffle数组
【发布时间】:2015-02-13 04:13:40
【问题描述】:

我正在学习如何在 java 中使用字符串和 onlclick。我在下面编写了一个程序,将三个名称打乱,然后将它们输出到三个按钮中。

当我点击 Paul 时,我希望消息显示在消息框中。由于保罗每次都会在一个按钮。我对如何将我的信息附加给保罗感到困惑。

Paul 由于使用了数组而四处移动。我知道这是一个棘手的问题,但我也知道,有一些非常聪明的人喜欢挑战。

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void generate(View view) {

        String [] names = new String[3];
        names[0] = "Bob";
        names[1] = "Paul";
        names[2] = "Mike";

        Button btn_a = (Button) findViewById(R.id.a);
        Button btn_b = (Button) findViewById(R.id.b);
        Button btn_c = (Button) findViewById(R.id.c);
        TextView message = (TextView)findViewById(R.id.message);

        Arrays.asList(names);

        Collections.shuffle(Arrays.asList(names));

        btn_a.setText(names[0]);
        btn_b.setText(names[1]);
        btn_c.setText(names[2]);

    }

    public void a1(View view) {
    }

    public void b1(View view) {
    }

    public void c1(View view) {
    }
}

【问题讨论】:

  • stackoverflow.com/a/12828267/2958086 为所有按钮分配相同的 ActionListener 但仅当按钮的文本为 Paul 时才执行操作。链接的答案显示如何使用名称,其后的答案显示如何使用文本。
  • 我阅读了您建议的链接。我有三个 onlick 按钮。如果他们受到压力,我知道如何让事情发生。由于保罗随机移动。我需要弄清楚如何将消息附加到保罗,因此当我按下保罗所在的按钮时,将显示一条消息。
  • 您可以将侦听器附加到所有三个按钮。当您使用检查文本的 if 语句时,具有文本 Paul 的按钮是唯一将执行操作的按钮。让它们都有相同的 ActionListener,只有 Paul 名字的按钮会响应它。
  • 您能否建议我如何在上面的代码中实现代码。这对我有很大帮助。我在过去 6 小时内搜索互联网没有成功。

标签: java arrays onclick shuffle


【解决方案1】:

这是Java 中的一个技巧 实用实现,其中单个侦听器用于多个按钮,而不是每个按钮一个侦听器,因此每个按钮的内容决定发生什么,而不是每个按钮的侦听器。帮助动态按钮网格(即 8x8 棋盘)不定义 64 个侦听器并将它们全部编码。

我手头没有 Android IDE,所以这是伪代码,但您应该能够从中了解要点。

//Create a Universal Listener for all our buttons
OnClickListener listener = new View.OnClickListener() {
    public void onClick(View v) {
        Button b = (Button)v;
        String text = b.getText().toString(); //get the button's name
        if(text.equals("Paul")) {
            //do anything for Paul ONLY in here
        }
    }
});

btn_a.setOnClickListener(listener); //give all the buttons the same listener, but only Paul's listener will do anything when you click on it
btn_b.setOnClickListener(listener);
btn_c.setOnClickListener(listener); 

使用来自:http://developer.android.com/reference/android/widget/Button.htmlhttps://stackoverflow.com/a/5620816/2958086 的信息

【讨论】:

  • 只需稍作调整即可。我的一天很成功,多亏了你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多