[英]Android: find the id of the inflated buttons
我使用以下代碼對按鈕進行了放大,並希望使用簡單的TranslateAnimation
交換選擇的2個按鈕的位置。
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();
}
}
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)
對於信息,如果selection%2 == 1,則表示用戶僅按下了第一個按鈕,還沒有准備好進行交換,因此需要記錄id及其X,Y坐標。 如果selection%2 == 0,則表示用戶已按下2個按鈕,並且在記錄第二個對象的X和Y之后可以進行交換。
另外,(X1,Y1)和(X2,Y2)坐標正確報告。
它在426行btn_right.clearAnimation();
處遇到NPE btn_right.clearAnimation();
(如上所述)。 我的問題是,由於所有按鈕都是膨脹的,並且我已經為所有膨脹的按鈕設置了setId,為什么它在第426行仍會作為NPE用盡,或者實際上我應該如何指定用戶觸摸過的2個按鈕來實現交換動畫?
謝謝!!
創建按鈕列表,您可以創建按鈕並設置其ID,標簽和onclicklistenners,並將其添加到按鈕列表中:
buttonList = new ArrayList<Button>();
for (int i=0;i<2;i++){
Button button = new Button(getApplicationContext());
button.setOnClickListener(customListenner);
button.setAnimation(anim);
button.setId(i);
button.setTag(i);
myLayout.addView(button);
buttonList.add(button);
}
當您需要再次使用該按鈕時,只需使用列表中的ID或標簽進行調用即可。 ( buttonList.get(0).getId()
)
如果需要不同的偵聽器,則可以通過使用獨特的標簽簽入if函數並聲明其他操作來控制它們。
這是我需要以編程方式在動態視圖上創建和使用動畫時經常使用的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.