gpt4 book ai didi

java - Android/Java - 单击 ListView 中的图像

转载 作者:行者123 更新时间:2023-12-02 03:41:42 24 4
gpt4 key购买 nike

我在 Android Studio 中制作了一个 ListView 。 ListView 的每个项目都有一个图像,但我不知道如何使其可点击。我确实在互联网上浏览了解决方案,但困难的部分似乎是在我自己的代码中实现它。我无法弄清楚。

相关图像 = ex_img

--请记住,当单击图像时,它还应该知道其在列表中的位置。

感谢您的阅读,希望您能帮助我。

列表适配器:

public class CustomList extends ArrayAdapter<String> {
private String[] ex_name;
private String[] ex_diff;
private String[] ex_muscle;
private String[] ex_dpr;
private Integer[] ex_img;
private Activity context;

public CustomList(Activity context, String[] ex_name, String[] ex_diff, String[] ex_muscle, String[] ex_dpr,
Integer[] ex_img) {
super(context, R.layout.row_layout, ex_name);
this.context = context;
this.ex_name = ex_name;
this.ex_muscle = ex_muscle;
this.ex_diff = ex_diff;
this.ex_dpr = ex_dpr;
this.ex_img = ex_img;

}
//LIST --> XML
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.row_layout, null, true);
TextView list_name = (TextView) listViewItem.findViewById(R.id.ex_name);
TextView list_diff = (TextView) listViewItem.findViewById(R.id.ex_diff);
TextView list_muscle = (TextView) listViewItem.findViewById(R.id.ex_muscle);
ImageView list_image = (ImageView) listViewItem.findViewById(R.id.ex_img);
TextView list_dpr = (TextView) listViewItem.findViewById(R.id.ex_dpr);

list_name.setText(ex_name[position]);
list_muscle.setText(ex_muscle[position]);
list_diff.setText(ex_diff[position]);
list_dpr.setText(ex_dpr[position]);
list_image.setImageResource(ex_img[position]);

return listViewItem;

}
}

可能需要的 MainActivity 部分:

 private Integer img[] = {
R.drawable.ic_favorite_white_24dp,
R.drawable.ic_location_on_white_24dp,
R.drawable.ic_update_white_24dp,
R.drawable.ic_local_dining_white_24dp,
R.drawable.ic_local_dining_white_24dp

};


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

CustomList customList = new CustomList(this, name, diff, muscle, dpr, img);

listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(customList);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"You Clicked "+name[i],Toast.LENGTH_SHORT).show();
}
});
}

最佳答案

onClickListener 添加到 getView() 中的 ImageView -

list_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Here you have the position too.
});

只需将getView()中的position参数设为final即可

关于java - Android/Java - 单击 ListView 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36778381/

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