我有一个由 textviews 构建的列表视图。
如果用户单击项目列表,单击项目的文本将被更改,我该怎么做?
我知道如何添加新项目,但更改其文本?我怎样才能做到这一点?
首先,您需要在 ListView 中添加一个OnItemClickListener:
mMyListView.setOnClickListener(new OnItemClickListener(
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
));
在OnItemClickListener的onItemClick方法中有一个视图参数。它包含已单击的 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(...);
}
您可以使用AdapterView.OnItemClickListener执行此操作。实现onItemClick(AdapterView<?> parent, View view, int position, long id)
方法。view
你在这里通过,是点击TextView
项目的,所以应该足够了
((TextView)view).setText("Hey, I've just been tapped on!");
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");
}
));
但是,如果您有自定义视图,则需要查找视图来更改文本:
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");
}
));