gpt4 book ai didi

java - click方法中的动态按钮和getTag

转载 作者:行者123 更新时间:2023-12-02 12:46:29 24 4
gpt4 key购买 nike

我正在尝试创建动态按钮并在其中添加点击功能。我尝试在按钮数组的元素中使用 getTag 方法。每当我尝试运行这些代码时,应用程序崩溃时我都会尝试,即 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 android.view.View.performClick(View.java:4757)
at android.view.View$PerformClick.run(View.java:19757)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.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.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

最佳答案

尝试使用这个:

Log.i("info", ""+v.getTag());  

或者如果你想将其解析为 int。

final int tag = Integer.parseInt(""+v.getTag());

关于java - click方法中的动态按钮和getTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com