简体   繁体   中英

Get clicked TextView in ScrollView/LinearLayout?

I have in my program a scroll view with a linearlayout inside of it. I add dynamically TextView's to the linearlayout and I have no way to know how much TextView's I'll end up with. When a certain TextView is clicked I need to get it's text. Any idea what is the best way to do it?

Thanks in advance.

I've tried to add a listener to the text view but I am not sure how to get the text. I saw in some posts that you can do a listener to the LinearLayour/ScrollView though I am not sure what is the best option.

This happenes every time a message is added:

TextView messageText = new TextView(RecordedMessagesScreen.this);
messageText.setText(content);
messageText.setClickable(true);

messageText.setOnClickListener(RecordedMessagesScreen.this.textViewListener);
RecordedMessagesScreen.this.messagesLayout.addView(messageText);

this is the listener:

this.textViewListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent data = new Intent();
        data.putExtra("message", ***NEED TO GET THE TEXT***)
    }
};

At the class level declare a String variable:

private String text = "";

and a View.OnClickListener variable:

private View.OnClickListener listener;

Initialize the listener in onCreate() of your activity like this:

listener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TextView tv = (TextView) v;
        text = tv.getText().toString();
    }
};

and every time you create a new TextView set the listener:

textView.setOnClickListener(listener);

This way the variable text each time you click a TextView will get the clicked TextView 's text.
You can customize the code inside onClick() yo suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM