Я использую кнопку, чтобы добавить новую кнопку во время выполнения, а также нужно изменить метку кнопки, но она отображает только предопределенные. Скажите, как изменить новую добавленную метку кнопки. Мой код для добавления новой кнопки:Сменить ярлык кнопки и добавить прослушиватель
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();
}
}
Чтобы сохранить кнопку создан Я использую SharedPreferences в OnCreate:
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 («любой текст») поможет вам изменить текст кнопки addNew –
Но мне нужно изменить текст кнопки во время выполнения. это даст кнопку с предопределенным текстом –
, какую часть кода вы хотите изменить текст кнопки? И вы хотите изменить текст новой кнопки? или старую кнопку? –