简体   繁体   English

将突出显示的文本应用于多个文本行

[英]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?或者我是否必须在每个要突出显示的文本正文中向 onClick 方法添加颜色线?

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.我在每个页面/屏幕上有 54 个答案,每组 3 个答案,并且必须对每个答案使用相同的方法 - 按下时突出显示。 I wonder how can I do it properly.我想知道我怎样才能正确地做到这一点。 If I add to findViewById(R.id.textView2);如果我添加到 findViewById(R.id.textView2); another text id right after textView2 this isn't working. textView2 之后的另一个文本 id 这不起作用。

You need to use textSelector for this.为此,您需要使用 textSelector。

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"你的 textView 将有 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.在代码中,您需要为 textView 编写 OnClickListener,而在 OnClick 中,您只需要指明textView.setSelected(true)这将使 textColor 变为绿色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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