我有一个从textviews构建的列表视图。
如果用户点击了一个项目列表,则所选项目的文本将被更改,我该怎么做?
我知道如何添加新项目,但更改其文字?我怎么能这样做?
答案 0 :(得分:7)
首先,您需要向OnItemClickListener添加ListView:
mMyListView.setOnClickListener(new OnItemClickListener(
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
));
在onItemClick的OnItemClickListener方法中,有一个 view 参数。它包含已单击的ListView行。
使用该视图,您可以获取TextView,然后更改文本:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view.findViewById(R.id.your_text_view_id);
tv.setText(...);
}
如果您的ListView单元格只包含TextView,您可以安全地将视图直接转换为TextView:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
tv.setText(...);
}
答案 1 :(得分:5)
您可以使用AdapterView.OnItemClickListener执行此操作。实现onItemClick(AdapterView<?> parent, View view, int position, long id)
方法。您在这里传递的view
是所点击商品的TextView
,所以它应该足够了
((TextView)view).setText("Hey, I've just been tapped on!");
答案 2 :(得分:2)
mListView.setOnClickListener(new OnItemClickListener(
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView mTextView = (TextView) view;
mTextView.setText("TextView was Clicked");
}
));
答案 3 :(得分:0)
如果你有一个简单的适配器,它会工作:
mListView.setOnClickListener(new OnItemClickListener(
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView mTextView = (TextView) view;
mTextView.setText("TextView was Clicked");
}
));
但是如果您有自定义视图,则需要查找视图以更改文字:
mListView.setOnClickListener(new OnItemClickListener(
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TextView mTextView = (TextView) view;
//mTextView.setText("TextView was Clicked");
((TextView)(view.findViewById(R.id.description))).setText(""TextView was Clicked");
}
));