我正在制作应用,其中一部分是在列表视图中添加注释(它是一个简单的膳食计划应用)。我一直在关注Lynda的课程,将其实施到我的项目中(为Android构建笔记应用程序(2013))。
我的活动和Java类中有3个ListView和3个按钮。 Java类中的ListViews名为mLBMon, mLLMon, mLDMon
(B,L,D表示早餐等,L表示ListView,Mon表示星期一)。 Buttons在XML中使用OnClick,android:onClick="onClick".
onClick方法是:
public void onClick(View v){
MealItem meal = MealItem.getNew();
Intent i = new Intent(this, MealEditor.class); // Meal Editor is the activity where the user enters the note which is displayed in the text view
i.putExtra("key", meal.getKey());
i.putExtra("text", meal.getText());
startActivityForResult(i, 1001);
}
当用户返回主页时,ListView会更新:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001 && resultCode == RESULT_OK){
MealItem meal = new MealItem();
meal.setKey(data.getStringExtra("key"));
meal.setText(data.getStringExtra("text"));
datasource.update(meal);
refreshDisplay();
}
}
refreshDisplay()
:
private void refreshDisplay() {
mealsList = datasource.findAll();
ArrayAdapter<MealItem> adapter =
new ArrayAdapter<MealItem>(this, R.layout.list_item_layout, mealsList);
mLBMon.setAdapter(adapter);
}
似乎mLBMon.setAdapater(adapter)
确定它显示在哪个ListView上,当我将其更改为mLLMon或mLDM时,它会显示在ListView上。
所以我要做的是当点击一个不同的按钮时,它会显示在ListView&#34;链接&#34;到那个按钮:
MondayLunchButton 点击 - &gt;用户在编辑器中做了注释。按下 - &gt; MondayLunchListView已更新
等
如果有人可以指导我朝着正确的方向前进,那将会很有帮助。如果需要,我很乐意提供更多代码。这是我第一次使用Android,我正在努力学习它,所以我决定做一个项目,所以如果我没有提供足够的信息,我很抱歉。感谢。
答案 0 :(得分:1)
对于按下的每个按钮,发送不同的request code
到MealEditor
启动意图。当它返回时你会得到完全相同的id。使用此ID来设置条件并相应地更新ListView
。
这样做
public void onClick(View v){
MealItem meal = MealItem.getNew();
Intent i = new Intent(this, MealEditor.class); // Meal Editor is the activity where the user enters the note which is displayed in the text view
i.putExtra("key", meal.getKey());
i.putExtra("text", meal.getText());
if(v.getId() == R.id.breakfast) // use your breakfast button id here
startActivityForResult(i, 1001);
else if(v.getId() == R.id.lunch) // use your lunch button id here
startActivityForResult(i, 1002);
else if(v.getId() == R.id.dinner) // use your dinner button id here
startActivityForResult(i, 1003);
}
然后
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == 1001 || requestCode == 1002 || requestCode == 1003) && resultCode == RESULT_OK){
MealItem meal = new MealItem();
meal.setKey(data.getStringExtra("key"));
meal.setText(data.getStringExtra("text"));
datasource.update(meal);
refreshDisplay(requestCode);
}
}
最后
private void refreshDisplay(int code) {
mealsList = datasource.findAll();
ArrayAdapter<MealItem> adapter =
new ArrayAdapter<MealItem>(this, R.layout.list_item_layout, mealsList);
if(code == 1001)
mLBMon.setAdapter(adapter);
else if(code == 1002)
mLLMon.setAdapter(adapter);
else if(code == 1003)
mLDMon.setAdapter(adapter);
}
注意:最好将1001
,1002
和1003
等值保存在int常量中,例如CODE_BREAKFAST
,{{1} },CODE_LUNCH
;这样你就不会误解CODE_DINNER
条件。