Android中怎样把Toast放在当前点击的listview中的item上
时间: 2024-01-21 20:19:14 浏览: 104
要在当前点击的ListView的item上显示Toast,可以使用以下步骤:
1. 在ListView的适配器中,为每个item添加点击事件监听器。
2. 在点击事件监听器中,获取当前点击的item的视图,并使用该视图的getContext()方法获取上下文。
3. 在上下文中使用LayoutInflater获取自定义的Toast布局,并为其设置文本等属性。
4. 调用Toast的setView()方法将自定义布局设置为Toast的视图。
5. 调用Toast的show()方法显示Toast。
下面是示例代码:
```java
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Context context = view.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View toastView = inflater.inflate(R.layout.custom_toast, null);
TextView text = toastView.findViewById(R.id.toast_text);
text.setText("You clicked item " + (position+1));
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastView);
toast.show();
}
});
```
其中,custom_toast是自定义的Toast布局文件,可以根据需要进行修改。
阅读全文
相关推荐


















