I have a very weird problem with my Android project. I have a 2d array of buttons and i am trying to add action listener to those. So this is what i have:
for ( i = 0; i<buttons.length;i++)
{
for ( k = 0; k<buttons[i].length;k++)
{
String but = "mtp" + i + k;
buttons[i][k] = (Button)v.findViewWithTag(but);
if (k%2 == 0)
{
buttons[i][k].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
text.setText(words[w]);
w++;
}
});
}
else
{
buttons[i][k].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int res = getResources().getIdentifier(icons[p],"drawable", getPackageName());
buttons[i][k].setBackgroundResource(res);
p++;
}
});
}
}
}
The weird thing is that my first action Listener works fine. It changes the TextView correctly. But the second one crashes my app. Moreover when i set an action listener not in a loop but outside of it like:
buttons[0][1].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int res = getResources().getIdentifier(icons[p],"drawable", getPackageName());
buttons[0][1].setBackgroundResource(res);
p++;
}
});
It works just fine. What do i do? How can i fix this?
Are these buttons in your XML file? Or are you trying to do it programmatically? Because you can implement the OnClickListener with your Activity.
Here's an alternative
XML:
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="button1"
android:text="@string/button1" />
Java:
public class YOUNAMEHERE extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void button1 (View v) {
*The things you want to happen when the button is pressed*
}
This shortens the amount of code you have to write and is easier to read since everything is implemented beforehand.
I know this doesn't really completely answer your question but I hope it helps. This is what I know so far about coding for Android with Java.
First of all you cannot use i
and k
variables in the anonymous class (inside new View.OnClickListener()
implementation) until it declared as final
.
Also, text
variable (as reference to some TextView object as I can see) have to be final too, so, it will reference to the same TextView in every iteration.
And you have to change
buttons[i][k].setBackgroundResource(res);
with something like
((Button)view).setBackgroundResource(res);
because when the onClick() handler will be called, the i
and k
variables will be invalid. But the onClick() argument named view
has actual reference to the view has been clicked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.