在我的应用程序中,当用户按下添加按钮图标时,会创建一个新按钮并弹出一个对话框,以便用户可以命名该按钮。但是,当用户关闭程序并重新打开它时,布局显然会重置。如何保存用户创建的按钮,即使他们杀死了应用程序?提前致谢。
答案 0 :(得分:0)
您可以使用共享偏好
public class MainActivity extends AppCompatActivity {
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkIfButtonNameAlreadyPresent();
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, /* name from the pop up */);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
public void checkIfButtonNameAlreadyPresent(){
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name = sharedpreferences.getString(Name, "");
if (name.equals("")){
b1.setText("Button");
} else {
//this should be executed if any name you added ever
b1.setText(name)
}
}
}