Android Button Problem
i am making a app which generate buttons according to the value entered by user. each button have have there own function defined in XML. Now my main problem is how to shorten these codes.
name[0].setClickable(true);
name[0].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
name[0].setText("kjghjbjhb");
}
});
name[2].setClickable(true);
name[2].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
name[2].setText("kjghjbjhb");
}
});name[1].setClickable(true);
name[1].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
name[1].setText("kjghjbjhb");
}
});
and soo on.....writing these codes again and again is开发者_如何学C not possible as button generated are dynamic, i dunno how many buttons will be generated. Please tell if there is a some other way to do this.
Something like this?
createButton(int i){
name[i].setClickable(true);
name[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
name[i].setText("kjghjbjhb");
}
});
}
With this method you can also make a for-loop:
for (int i = 0; i<name.length; i++){
createButton(i);
}
Here I am specifying the steps to be executed.
- You must be creating the buttons by new Button(); just hold its reference in a Collection say ArrayList
ArrayList ar = new ArrayList();
Button b1 = new Button();
ar.add(b1);
- Now create a private inner class which is implementing the
View.OnClickListener
. Now as per rules implement theOnClick()
and so the stuff which you want to be done at there
class A extends Activity{
// your stuff here for OnCreate and other business logic
private final class MyListener implements View.OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
v.setText("kjghjbjhb");
}
}
}
Notice that I am setting the text with the reference of object v in onClick
. Also make this class singleton.
- Now set create the instance of this class (as the
MyListerner
will be singleton the object will be one) in thesetOnClickListener()
like this:
MyListener listener = MyListener.getInstance();
b.setOnClickListener(listener);
You can opt this way when the buttons are created on some event or user action. In case if you need to create the buttons in loop you can use the 1st and 3rd step in loop.
精彩评论