2 回答
TA贡献1863条经验 获得超2个赞
您在执行插入操作的循环中使用相同的 EditText,这是您以编程方式创建的 3 个中的最后一个。
代替:
EditText editText;
使用数组存储 3 个 EditText:
EditText[] editText;
并将代码更改为:
LinearLayout ll;
EditText[] editText;
TextView textView;
String room;
Button save;
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));
ll = findViewById(R.id.ll);
final int num = Integer.valueOf(room_number);
dbHelper = new DBHelper(this);
editText = new EditText[num];
for (int i = 0; i < num; i++) {
editText[i] = new EditText(this);
editText[i].setHint("Room " + (i + 1) + " Name");
textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ll.addView(editText[i]);
ll.addView(textView);
}
save = new Button(this);
save.setText("save");
ll.addView(save);
save.setOnClickListener(v -> {
for (int j = 0; j < num; j++) {
if (dbHelper.insertRoom(editText[j].getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}
});
}
TA贡献1777条经验 获得超10个赞
你的做法不正确。您应该为每个 EditText 使用 Tag 并通过它的 Tag 获取每个 EditText。
LinearLayout ll;
EditText editText;
TextView textView;
String room;
Button save;
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));
ll = findViewById(R.id.ll);
final int num = Integer.valueOf(room_number);
dbHelper = new DBHelper(this);
for (int i = 0; i < num; i++) {
editText = new EditText(this);
editText.setHint("Room " + (i + 1) + " Name");
//set tag for edit text
editText.setTag(i);
textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ll.addView(editText);
ll.addView(textView);
}
save = new Button(this);
save.setText("save");
ll.addView(save);
save.setOnClickListener(v ->{
for (int j = 0; j < num; j++){
if(dbHelper.insertRoom(editText.findViewWithTag(j).getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}
});
}
添加回答
举报