2017-08-06 51 views
-1

以下是代碼。每當我點擊Gridview中的任何一個項目時,我想打開一個新的活動。請幫忙。我知道我們將要使用開關盒,但不知道如何。如何在GridView中使用OnclickListener

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //set grid view item 
    Bitmap homeIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.home); 
    Bitmap userIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.personal); 

    gridArray.add(new Item(homeIcon,"Home")); 
    gridArray.add(new Item(userIcon,"User")); 
    gridArray.add(new Item(homeIcon,"House")); 
    gridArray.add(new Item(userIcon,"Friend")); 
    gridArray.add(new Item(homeIcon,"Home")); 
    gridArray.add(new Item(userIcon,"Personal")); 
    gridArray.add(new Item(homeIcon,"Home")); 
    gridArray.add(new Item(userIcon,"User")); 
    gridArray.add(new Item(homeIcon,"Building")); 
    gridArray.add(new Item(userIcon,"User")); 
    gridArray.add(new Item(homeIcon,"Home")); 
    gridArray.add(new Item(userIcon,"xyz")); 


    gridView = (GridView) findViewById(R.id.gridView1); 
    customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray); 
    gridView.setAdapter(customGridAdapter); 
} 

}

+0

已經回答。閱讀此https://stackoverflow.com/a/14675753/6266949 –

+2

你應該在提問之前做研究 –

+0

我已經完成了研究,但我無法弄清楚如何編輯代碼來打開新的活動。請指導我糾正我的代碼,以便在每次點擊時開啓新的活動。我知道我們將要使用開關盒,但不知道如何... –

回答

1

定義的意圖

Intent intent; 

然後定義一個項目單擊監聽你的GridView。

gridView.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View v, 
      int position, long id) { 

     switch (position) { 
      case 0: 
       //Depending on the position, define your intent 
       intent = new Intent(this, NewActivity.class); 
       startActivity(intent) 
       break; 
      //further cases 
     } 

    } 
}); 
相關問題