【发布时间】:2017-06-01 20:29:30
【问题描述】:
我正在使用一个按钮在运行时创建新按钮,但创建的新按钮具有预定义的标签,即btn1.setText("New");。有没有什么办法可以使在运行时创建的按钮可以修改或更改为其他标签,例如 New 它可以是“单击”、“鼠标”、“服装”,但在应用程序中在跑。
创建按钮的代码:
if(v == add){
Button btn1 = new Button(this);
btn1.setText("New");
btn1.setId(34);
btn1.setOnClickListener(this);
btn1.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View v){
mDialog();
}
});
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btn1, lp);
count++;
Editor editor = prefs.edit();
editor.putInt("count", count);
editor.commit();
}
我正在使用共享首选项来存储以前创建的按钮
prefs = PreferenceManager.getDefaultSharedPreferences(this);
count=prefs.getInt("count", 0);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
for(i=0;i<count;i++){
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button myButton = new Button(this);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
mDialog(myButton.getText().toString());
}
});
myButton.setId(34);
myButton.setText("New");
myButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View arg0) {
AlertDialog mdialog = new AlertDialog.Builder(context).create();
mdialog.setTitle("Change Button Label");
mdialog.setIcon(android.R.drawable.ic_dialog_info);
mdialog.setMessage("Enter new Button label to change");
final EditText input = new EditText(MainActivity.this);
mdialog.setView(input);
mdialog.setButton(DialogInterface.BUTTON_POSITIVE, "Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
myButton.setText(input.getText());
}
});
mdialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Button Label not Changed",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
mdialog.show();
return true; // <- set to true
}
});
ll.addView(myButton, lp);
}
【问题讨论】:
-
是的,您可以,在stackoverflow.com/questions/21497816/… 上查看我的回答,声明您的按钮并为此使用
setText方法。 -
setText不起作用? -
你能接受用户输入的标签吗?或者这个动态标签文本来自哪里
-
将所有标签存储在ArrayList中,并根据您的要求获取它们。或增量条件
-
@user2450263 来自用户意味着用户将能够根据他的要求更改按钮标签。