gpt4 book ai didi

android - 如何从 gridView 中单击的图像中获取资源名称?

转载 作者:行者123 更新时间:2023-11-29 15:15:53 24 4
gpt4 key购买 nike

我有一个 GridView,想获取被点击资源的名称(例如 R.drawable.foo1),但我不知道如何获取。

这是我的 fragment 中我想要获取名称的地方:

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
};
}

最佳答案

公开 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];
}

关于android - 如何从 gridView 中单击的图像中获取资源名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23950961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com