I have 80 buttons which the user must be able to rename with a long click event and save the new button text. When the user closes the app it must remain the same text and must NOT go back to default text. This is what i have for the first button. How will i do this so that it know which button is long pressed and to rename that. (This coding doesn't save it when i go out)
public class MainActivity extends AppCompatActivity {
private Button btn1 , btn2 , btn3 , btn4 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View.OnLongClickListener listener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showPopup(v);
return true; //Nothing shows error, but this part where i tried to set a onLongClick listener.
}
};
btn1.setOnLongClickListener(listener);
btn2.setOnLongClickListener(listener);
btn3.setOnLongClickListener(listener);
btn4.setOnLongClickListener(listener);
SharedPreferences prefs = getSharedPreferences("btnID", Context.MODE_PRIVATE);
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Button button = (Button) findViewById(Integer.parseInt(entry.getKey()));
button.setText(entry.getValue().toString());
}
}
private void showPopup(View v) {
//here you have your button
final Button currentButton = (Button)v;
v.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showPopup(v);
return true;
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Rename to?");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_view, null);
final EditText edit_dialog = (EditText)view.findViewById(R.id.edit_dialog);
edit_dialog.setText(currentButton.getText().toString());
builder.setView(view);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
currentButton.setText(edit_dialog.getText().toString());
SharedPreferences prefs = getSharedPreferences("btnID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(String.valueOf(currentButton.getId()), currentButton.getText().toString());
editor.apply();
}
});
builder.show();
}
}