我创建了一个简单的列表视图。我有两个列表视图,我的第一个列表视图只显示项目名称为水果的一个项目。如果我在列表视图中单击水果,它将转到第二个列表视图。第二个列表视图显示许多水果名称。如果我选择一个水果我想在我的第一个列表视图中显示水果名称(我希望在我的第一个列表视图中绑定该水果名称)所以,我使用的是onitemselectedlistener但它不起作用。如果我点击我的第二个列表视图水果名称没有任何发生....请检查我的源代码并帮助我....
第一个列表视图:
public class bview extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, cat)); getListView().setTextFilterEnabled(true); }
static final String[] cat = new String[] { "Category", };
protected void onListItemClick(ListView parent, View v, int position,long id) {
Intent intent= new Intent(bview.this,listview.class);
startActivity(intent);
//intent.putExtra("value", value); }}
第二个列表视图:
public class listview extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.submain);
ListView mlistView = (ListView) findViewById(R.id.listview);
mlistView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
new String[] {"orange", "apple","mango","banana","grapes"}));
mlistView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3){
Intent in2 =new Intent(listview.this, bview.class);
startActivity(in2);
}
public void onNothingSelected(AdapterView<?>arg0){
}});
}}
答案 0 :(得分:1)
您的问题是您没有将第二个列表中选择的内容传递回第一个列表。您需要包含在意图中选择的内容,然后在第一个活动中,您需要检查它是否包含在它启动的Intent中。所以你就是这样的。
在你的第二项活动中:
mlistView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3){
Intent in2 =new Intent(listview.this, bview.class);
in2.putExtra("SELECTED_ITEM", (String)arg0.getItemAtPosition(arg2));
startActivity(in2);
}
public void onNothingSelected(AdapterView<?>arg0){
}});
在您的第一个活动中,您需要在onCreate方法中添加此代码:
Intent givenIntent = getIntent();
if(givenIntent.hasExtra("SELECTED_ITEM")){
String selectedItem = givenIntent.getStringExtra("SELECTED_ITEM");
//now do what ever you want with the face that you have the item that was selected
}
else{
//in here you know the activity was started by selecting something from your second
//activity. so do what you need to do in that case here.
}