【发布时间】:2014-01-16 07:37:34
【问题描述】:
我正在使用一个按钮在运行时添加新按钮,并且还需要更改按钮标签,但它只显示预定义的。可以告诉我如何更改新添加的按钮标签。我添加新按钮的代码:
addnew = (Button)findViewById(R.id.btnaddnew);
addnew.setOnClickListener(this);
public void onClick(View v) {
if(v == addnew)
{
Button myButton = new Button(this);
myButton.setText("New Button");
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
count++;
Editor editor = prefs.edit();
editor.putInt("count", count);
editor.commit();
}
}
要存储创建的按钮,我在 onCreate 中使用 SharedPreferences:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
count=prefs.getInt("count", 0);
for(int i=0;i<count;i++){
Button myButton = new Button(this);
myButton.setText("New Button");
myButton.setId(count);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
我们也可以像我的其他按钮一样在添加的按钮上应用 onClickListener。代码:
bdialog = (Button)findViewById(R.id.btndialog);
property.setOnClickListener(this);
public void onClick(View v) {
if(v == bdialog)
{
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert_layout);
Button report = (Button) dialog.findViewById(R.id.btn_Report);
report.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"You clicked on Report", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancel = (Button) dialog.findViewById(R.id.btn_Cancel);
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Reverting Changes", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// Showing Alert Dialog
dialog.show();
}
我正在为我的对话框使用预定义的 xml 布局
【问题讨论】:
-
addnew.setText("whatever text") 将帮助您更改 addNew 按钮的文本
-
但我需要在运行时更改按钮文本。这将提供一个带有预定义文本的按钮
-
您希望更改按钮文本的哪部分代码??你想改变新按钮的文字吗?还是旧按钮?
-
我想更改添加的新按钮的文本,而不是用于添加新按钮的旧按钮
-
您编写的代码可以很好地添加新按钮,并且 btn.setText() 确实将按钮的文本设置为 "" ,而不是 "" 放置您想要的文本跨度>