3

我有一个由 textviews 构建的列表视图。

如果用户单击项目列表,单击项目的文本将被更改,我该怎么做?

我知道如何添加新项目,但更改其文本?我怎样才能做到这一点?

4

4 回答 4

7

首先,您需要在 ListView 中添加一个OnItemClickListener

mMyListView.setOnClickListener(new OnItemClickListener(
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }
));

OnItemClickListeneronItemClick方法中有一个视图参数。它包含已单击的 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(...);
}
于 2012-08-29T19:15:27.520 回答
5

您可以使用AdapterView.OnItemClickListener执行此操作。实现onItemClick(AdapterView<?> parent, View view, int position, long id)方法。view你在这里通过,是点击TextView项目的,所以应该足够了

((TextView)view).setText("Hey, I've just been tapped on!");
于 2012-08-29T19:11:54.287 回答
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");
    }
));
于 2012-08-29T19:20:50.847 回答
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");
    }
));
于 2017-04-10T22:30:55.523 回答