单击方法中的java动态按钮和getTag
我正在尝试创建动态按钮,并在其中添加单击功能。我试图在button数组的元素中获取Tag方法。每当我尝试运行这些代码时,应用程序崩溃,我都会同时尝试,即v.getTag()和button。getTag()。谢谢你帮助我
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testing);
//test creating of dynamic buttons
Button[] myButton = new Button[4];
LinearLayout scrViewButLay = (LinearLayout) findViewById(R.id.layout);
for (int index = 0; index < 4; index++) {
myButton[index] = new Button(this); //initialize the button here
myButton[index].setText("Button # ");
myButton[index].setTag(index);
scrViewButLay.addView(myButton[index]);
myButton[index].setOnClickListener(getOnClickDoSomething(myButton[index]));
}
}
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
//Log.i("info",(String) button.getTag());
Log.i("info",(String) v.getTag());
}
};
}
}
LogCat错误-------------------------------------------------------------------
com.example.mandeep.pos1_1, PID: 26112
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at com.example.mandeep.pos1_1.MainActivity$1.onClick(MainActivity.java:43)
at 安卓.view.View.performClick(View.java:4757)
at 安卓.view.View$PerformClick.run(View.java:19757)
at 安卓.os.Handler.handleCallback(Handler.java:739)
at 安卓.os.Handler.dispatchMessage(Handler.java:95)
at 安卓.os.Looper.loop(Looper.java:135)
at 安卓.app.ActivityThread.main(ActivityThread.java:5219)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.安卓.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:693)
# 1 楼答案
试着用这个:
或者如果你想把它解析成int