简体   繁体   中英

Applying highlighting text to multiple text lines

I'd like to ask you what global code do I have to create to highlight text when pressed in various places of the app. Or do I have to just add color line to onClick method in every single text body which is going to be highlighted?

Thanks for your advice.

To be more specific with my question, just have a look at this code:

public class MainActivity extends AppCompatActivity {
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text = (TextView) findViewById(R.id.textView2);
        text.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                text.setTextColor(Color.GREEN);
            }
        });
    }
}

I have 54 answers in sets of 3 answers on every page/screen and have to use the same method for each answer - being highligted when pressed. I wonder how can I do it properly. If I add to findViewById(R.id.textView2); another text id right after textView2 this isn't working.

You need to use textSelector for this.

Please refer the link below for how to write selector -

Android customized button; changing text color

In your case, if you want the text color to be green after selection, your selector should be like this -

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false" android:color="defalutColor" />
    <item android:state_selected="true" android:color="greenColor" />
</selector>

And your textView will have textColor="@drawable/textSelector"

And in code you need to write OnClickListener for textView and in OnClick you just need indicate textView.setSelected(true) this will make the textColor green.

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