[英]Setting Button text with an array item
I'm trying to set the text of a button from an array using a AlertDialog. 我正在尝试使用AlertDialog从数组设置按钮的文本。 I can bring up the array within the AlertDialog with no problem but how do I set the text to the item chosen?
我可以毫无问题地在AlertDialog中调出数组,但是如何将文本设置为所选项目呢? Any help would be appreciated, thanks.
任何帮助,将不胜感激,谢谢。
Here's my array 这是我的数组
<string-array name="Months">
<item>January</item>
<item>February</item> <item>March</item> <item>April</item>
<item>May</item> <item>June</item> <item>July</item>
<item>August</item> <item>September</item> <item>October</item>
<item>November</item> <item>December</item>
</string-array>
And here is where I want to set the text 这是我要设置文字的地方
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select a month");
builder.setItems(R.array.Months, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
button.settext(""); // how do i set the text of the chosen item
}
});
builder.create().show();
return false;
}
});
试试这个: getResources().getStringArray(R.array.Months)[which];
I would recommend doing it like this: 我建议这样做:
String[] months = { "January", "February", "March", ... "December" };
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select a month");
builder.setItems(months, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
button.setText(months[which]);
}
});
builder.create().show();
return true;
}
});
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.