Android-SharedPreferences与EditText,使用For Loop创建



我用"for loop"创建了EditTexts,我想使用SharedPreferences保存EditText中的数据。我可以通过xml创建EditTexts来管理它,但这需要大量的时间和精力。您可以在下面看到代码。使用第二个"for 循环",我已经创建了 15 个 EditText(数量会增加(,我想存储来自这些 EditText 的数据以进行一些计算。如何将共享首选项与"for loop"一起使用这些编辑文本?

public class MainActivity extends AppCompatActivity {
private ScrollView sV;
private LinearLayout pnl;
private GridLayout gL;
private TextView tV;
private Button btn;
private EditText eT;
private void init() {
sV = new ScrollView(this);
hsV = new HorizontalScrollView(this);
pnl = new LinearLayout(this);
pnl.setOrientation(LinearLayout.VERTICAL);
gL = new GridLayout(this);
gL.setColumnCount(2);
final String[] title = getResources().getStringArray(R.array.title);
final String[] info = getResources().getStringArray(R.array.info);
for (int j = 0; j < 2; j++) {
tV = new TextView(this);
tV.setText(title[j]);
tV.setTextSize(20);
tV.setTypeface(Typeface.DEFAULT_BOLD);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
}
for (int i = 0; i < 15; i++) {
tV = new TextView(this);
tV.setText(info[i]);
tV.setTextSize(20);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
gL.addView(eT);
}
btn = new Button(this);
btn.setText("Save");
gL.addView(btn);
pnl.addView(gL);
sV.addView(pnl);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView(sV);
}
}

您可以在 EditText 上添加标签来识别它们。

然后,您可以将这些标签用作共享首选项中的键,如下所示:

for (int i = 0; i < 15; i++) {
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
// adding a tag to identify the EditText
String tag = "edit" + i;
eT.setTag(tag);
gL.addView(eT);
}

如何存储

@Override
public void afterTextChanged(Editable editable) {
// get values
String key = (String)editable.getTag()
String value = editable.getText().toString()
// save in SharedPreferences
sharedPreferencesEditor.putString(key, values)
sharedPreferencesEditor.commit()
}

最新更新