2016-12-11 58 views
0

我試圖從gridView中獲取項目的名稱,因爲它在可繪製文件夾中的名稱。請幫我從gridView中獲取名稱。 這是我的ImageAdapter。如何通過單擊gridView上的項目來獲取可繪製的項目名稱

package com.example.test.griddemo.CategoriesPackage; import android.content.Context;導入android.view.View;導入android.view.ViewGroup;導入android.widget.BaseAdapter;導入android.widget.GridView;導入android.widget.ImageView; import com.example.test.griddemo.R; /** *由Sabir Hossain在12/10/2016創建。 */ 公共類CategoriesImageAdapter延伸BaseAdapter {

private Context CTX; private int[] imageId = {R.drawable.cakecatag,R.drawable.furitecategroie,R.drawable.graincatag, 
       R.drawable.ricecatag,R.drawable.meatcatag,R.drawable.vegetablecatag,  R.drawable.groceriescatag}; 
    public CategoriesImageAdapter (Context ctx){ 
    this.CTX = ctx; } 
    @Override public int getCount() { 

    return imageId.length; } 
    @Override public Object getItem(int position) { 
    return imageId[position]; } 
    @Override public long getItemId(int position) { 
    return position; } 
    @Override public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView img; 

    if(convertView == null){ 
     img = new ImageView(CTX); 
     img.setLayoutParams(new GridView.LayoutParams(360,360)); 
     img.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     img.setPadding(8,8,8,8); 
    }else{ 
     img = (ImageView) convertView; 
    } 
    img.setImageResource(imageId[position]); 

    return img; } } 
    Here is OnItemClicListener 
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

      String name = view.getResources().getResourceEntryName(); 
      Toast.makeText(getContext(),"Cilicked "+gridView.getItemAtPosition(position),Toast.LENGTH_SHORT).show(); 
     } 
    }); 

回答

0

怎麼這樣呢?

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     int resID = imageId[position]; 
     String resName = CTX.getResources().getResourceEntryName(resID); 
     // ... 
    } 
});