我有一个GridView,想要获取所点击资源的名称(例如R.drawable.foo1),我不知道如何。
这是我的片段中我希望获得名称的地方:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(getActivity()));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO HERE I WANT TO GET THE NAME
}
});
return rootView;
}
}
我有以下适配器:
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.foo1, R.drawable.foo2, R.drawable.foo3
};
}
答案 0 :(得分:2)
将mThumbIds设为公开:
public Integer[] mThumbIds = {
R.drawable.foo1, R.drawable.foo2, R.drawable.foo3
};
在onItemClicked()中获取图像资源名称,如下所示:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int id = mImageAdapter.mThumbIds[position];
}
答案 1 :(得分:2)
在mThumbIds
中添加Fragment
,然后使用Drawable
中的mThumbIds
直接从Position
获取onItemClick(.....)
。
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//mThumbIds[position]; get particular Drawable from mThumbIds
}
});
答案 2 :(得分:1)
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
int res = ((ImageAdapter)parent).getResource(position);
}
});
然后在适配器中使用此方法获取图像资源:
public void getResource(int pos){
return mThumbIds[position];
}