idish
idish

Reputation: 3260

ListView change text on item click

I have a listview that is built from textviews.

If the user clicks an item list, the text of the clicked item will be changed, how can I do that?

I know how to add new item, but changing its text? How can I do that?

Upvotes: 3

Views: 18542

Answers (4)

Jorgesys
Jorgesys

Reputation: 126445

Well it will work if you have a simple Adapter:

mListView.setOnClickListener(new OnItemClickListener(
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView mTextView = (TextView) view;
        mTextView.setText("TextView was Clicked");
    }
));

But if you have a custom view you need to look for the View to change the text:

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");
    }
));

Upvotes: 0

Swayam
Swayam

Reputation: 16354

 mListView.setOnClickListener(new OnItemClickListener(
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView mTextView = (TextView) view;
        mTextView.setText("TextView was Clicked");
    }
));

Upvotes: 2

ol_v_er
ol_v_er

Reputation: 27284

First of all, you need to add a OnItemClickListener to your ListView:

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

In the method onItemClick of the OnItemClickListener there is an view parameter. It contains the row of the ListView which has been clicked.

With that view, you can get the TextView and then change the text:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    TextView tv = (TextView) view.findViewById(R.id.your_text_view_id);
    tv.setText(...);
}

If your ListView cell only contains a TextView, you can safely cast the view directly into a TextView:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    TextView tv = (TextView) view;
    tv.setText(...);
}

Upvotes: 7

Ridcully
Ridcully

Reputation: 23655

You can do this with an AdapterView.OnItemClickListener. Implement the onItemClick(AdapterView<?> parent, View view, int position, long id) method. The view you get passed here, is the TextView of the clicked item, so it should be enough to do

((TextView)view).setText("Hey, I've just been tapped on!");

Upvotes: 5

Related Questions