Ich möchte & speichern Schaltfläche Text onLongClick dauerhaft speichern (bis &, es sei denn, ich ändere es erneut). This ist ein Screenshot des gesamten Codes. Aber wenn ich die App & wieder öffne, bleibt der Button-Text Standard. Welchen Fehler mache ich?Ändern und Speichern Button Text onLongClick using sharedpreferences
package com.demo.buttontextedit;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
private Button btn;
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
edit = (EditText) findViewById(R.id.edit_text);
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showDialog(edit.getText().toString());
return true;
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You clicked Button" +
btn.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void showDialog(String str) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("input text");
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(str);
builder.setView(view);
builder.setNegativeButton("cancel", null);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Name", edit_dialog.getText().toString());
editor.commit();
btn.setText(sharedPreferences.getString("Name", ""));
}
});
builder.show();
}
}
Sie müssen Ihren Schaltflächentext von 'onCreate()' entsprechend dem Wert in sharedpreference aktualisieren. – Rashin