Learningmind
Learningmind

Reputation: 127

how to use java onclick shuffle array

I am learning how to use strings and onlclick in java. I have written a programme below which shuffle three names and then outputs them into three buttons.

When I click on Paul, I want the message to be displayed in message box. Since Paul will be in a button each time. I am puzzled on how to attach my message to Paul.

Paul moves around due to the use of array. I understand this is a tough question, but I also know, there are some very clever ppl out there who love a challenge.

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) {
    }
}

Upvotes: 0

Views: 502

Answers (1)

Compass
Compass

Reputation: 5937

This is a trick practical implementation in Java where a single listener is used for multiple buttons, rather than one listener for each button, so that each button's content determines what happens, not each button's listener. Helps for dynamic button grids (i.e. an 8x8 chessboard) to not define 64 listeners and code them all.

I don't have an Android IDE on hand, so this is pseudo-code, but you should be able to get the gist from this.

//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); 

Using info from: http://developer.android.com/reference/android/widget/Button.html and https://stackoverflow.com/a/5620816/2958086

Upvotes: 2

Related Questions