I'm using a button to create new button's on runtime but the new buttons created have predefined label i.e. btn1.setText("New");
. Is there any way so that once buttons created on runtime there label can be modified or change to some other label like instead of New it can be "Click", "mouse", "clothing" but while application is running.
code to create button:
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();
}
And I'm using shared preferences to store previous created buttons
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);
}