У меня есть Button
, который динамически создает EditText
s. У меня нет проблем с созданием их при запуске приложения, но ни один из созданных EditText
s не сохраняется при закрытии приложения и его повторном открытии. Вот мой код:Динамически созданный EditText's
public class app extends ActionBarActivity {
Button add;
LinearLayout linearLayout1;
static int createEditText;
public static final String TAG = "MyPrefs" ;
public static final String key1 = "numberOfEditTexts"; //Added this
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
linearLayout1 = (LinearLayout)findViewById(R.id.linearLayout1);
add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createEditText();
}
});
}
public void createEditText() {
Log.i("ET", "ET created");
createEditText++;
if(createEditText > 6) {
Toast.makeText(this, "You have reached the maximum fields",
Toast.LENGTH_LONG).show();
return;
}
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(0, 12, 0, 0);
EditText edtTxt = new EditText(this);
int maxLength = 8;
edtTxt.setHint("New ET1");
edtTxt.setLayoutParams(params);
edtTxt.setBackgroundColor(Color.WHITE);
edtTxt.setInputType(InputType.TYPE_CLASS_DATETIME);
edtTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edtTxt.setFilters(fArray);
edtTxt.setGravity(Gravity.CENTER);
layout.addView(edtTxt);
edtTxt.setId(createEditText);
}
@Override //Added this
protected void onPause() {
super.onPause();
Log.i("Pause", "onPause()");
System.out.println("EditText = " + createEditText);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key1, createEditText);
editor.commit();
}
@Override //Added this
protected void onResume(){
super.onResume();
Log.i("Resume", "onResume()");
System.out.println("EditText = " + createEditText);
sharedPreferences.getInt(key1, createEditText);
}
Если вы хотите сохранить данные, сохраненные между различными запусками активности, вы можете прочитать о 'SharedPreferences' [здесь] (http://developer.android.com/reference/android/content/SharedPreferences.html) –