2013-03-12 55 views
0

如何从我的GridView中将正确的值传递给我的意图。看来我这样做是错误的。因此,这里是我所做的:Android- onItemClick将正确的值传递给intent

在我的MainActivity:

CategoryRowItem category; 
. 
. 
. 
//after parsing from json 
category = new CategoryRowItem(catId, catName); 
categoryItems.add(category); 

gridView = (GridView) findViewById(R.id.grid_view); 
final CustomBaseAdapter adapter = new CustomBaseAdapter(this, categoryItems); 
gridView.setAdapter(adapter); 

gridView.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View view, int position, long id){ 
      String categoryId = category.getCatId(); // i think this not right 
      String categoryName = category.getCatName(); 
      System.out.println("CAT ID: " +categoryId); 
      Intent intent = new Intent(getApplicationContext(), ShopListActivity.class); 
      intent.putExtra("catID", categoryId); 
      intent.putExtra(CATEGORY, categoryName); 
      startActivity(intent); 
     } 
    }); 

我CategoryRowItem类: 这有getter和setter

public String getCatId(){ 
    return catId; 
} 

public String getCatName(){ 
    return catName; 
} 
    public void setCatId(String cId){ 
    this.catId = cId; 
} 

public void setCatName(String name){ 
    this.catName = name; 
} 

所以,我怎样才能得到这样的CATID正确的价值,或者点击物品的catName>

回答

1

position会告诉你列表中的哪个项目被点击/选中,并且使用它可以获得您的CategoryRowItem及其细节。

CategoryRowItem category = categoryItems.get(position); // Add this line here. 
String categoryId = category.getCatId(); // Now this will be right. 
String categoryName = category.getCatName(); 
+0

感谢,但没有奏效。它仍然获得相同的ID。 – elL 2013-03-12 10:29:15

+0

哦,我明白了。谢谢。 – elL 2013-03-12 10:34:48

1
gridView.setOnItemClickListener(new OnItemClickListener() { 

    public void onItemClick(AdapterView<?> parent, View view, int position, long id){ 
     String categoryId = categoryItems.get(position).getCatId(); // i think this not right 
     String categoryName = categoryItems.get(position).getCatName(); 
     System.out.println("CAT ID: " +categoryId); 
     Intent intent = new Intent(getApplicationContext(), ShopListActivity.class); 
     intent.putExtra("catID", categoryId); 
     intent.putExtra(CATEGORY, categoryName); 
     startActivity(intent); 
    } 
}); 

与电网听众将这段代码