I have inflated buttons using the following codes, and would like to swap the location of the 2 buttons selected using simple TranslateAnimation
.
Codes:
for (int k = 1; k <= quotient; k++)
{
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(button_width,row_height);
params3.setMargins(button_margin, button_margin, button_margin, button_margin);
btn_right = new Button(this);
btn_right.setId(idd);
final int id_ = btn_right.getId();
btn_right.setText(""+question[idd]);
frame_row.addView(btn_right, params3);
btn_right.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
btn_right = ((Button) findViewById(id_));
X1 = getRelativeLeft(btn_right);
Y1 = getRelativeTop(btn_right);
int b = Integer.parseInt(""+btn_right.getText().toString());
selection ++;
if (selection%2 ==1)
{
selected_id1 = id_;
selected_color1 = b;
custom_toast("X1=" +X1 + "\nY1=" + Y1);
}
else
{
selected_id2 = id_;
selected_color2 = b;
X2 = getRelativeLeft(btn_right);
Y2 = getRelativeTop(btn_right);
custom_toast("X2=" +X2 + "\nY2=" + Y2);
// the first one
btn_right = ((Button) findViewById(selected_id1));
anim1=new TranslateAnimation(0, (X2-X1), 0, (Y2-Y1));
anim1.setFillAfter(true);
anim1.setDuration(animationTime);
anim1.setAnimationListener(Game.this);
btn_right.startAnimation(anim1);
// the second one
btn_right = ((Button) findViewById(selected_id2));
anim2=new TranslateAnimation(0, (X1-X2), 0, (Y1-Y2));
anim2.setFillAfter(true);
anim2.setDuration(animationTime);
anim2.setAnimationListener(Game.this);
btn_right.startAnimation(anim2);
}
@Override
public void onAnimationEnd(Animation animation)
{
if (animation == anim1)
{
custom_toast("1 clear");
btn_right = ((Button) findViewById(selected_id1));
btn_right.clearAnimation(); // Line 426
}
if (animation == anim2)
{
custom_toast("2 clear");
btn_right = ((Button) findViewById(selected_id2));
btn_right.clearAnimation();
}
}
Logcat:
04-21 21:28:00.728: E/AndroidRuntime(11341): java.lang.NullPointerException
04-21 21:28:00.728: E/AndroidRuntime(11341): at com.abc.abc.Game.onAnimationEnd(Game.java:426)
Question:
For info, if selection%2 ==1, it means user has only pressed the first button and is not yet ready for swap, and hence to record the id and its X, Y coordinates. If selection%2 ==0, it means user has pressed 2 buttons and is ready to swap after recording the 2nd's X and Y.
Also, the (X1, Y1) and (X2, Y2) coordinates are reporting correctly.
It runs into a NPE at line 426 btn_right.clearAnimation();
(as specified above) . My question is, since all the buttons are inflated, and I have already setId for all the inflated buttons, why it would still runs out as a NPE at line 426, or actually how should I specify the 2 buttons that the user has touched so as to implement the swapping animation?
Thanks!!