Search code examples
javaandroidandroid-linearlayouttextviewandroid-scrollview

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

Solution

  • 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.