选中时以红色突出显示 TextView 并在选中后保持突出显示

Highlight TextView in red when selected and keep highlight after selected

我有 3 个文本视图,如下所示。一旦我点击其中一个,它就会变成红色,但当我取消选择它时又会恢复到默认颜色。我想将选定的 TextView 保持为红色。我在一个片段中有这 3 个 TextView。

mQuickReturnView = (TextView) view.findViewById(R.id.footer);
mQuickReturnView1 = (TextView) view.findViewById(R.id.footer1);
mQuickReturnView2 = (TextView) view.findViewById(R.id.footer2);

TextView clickTextView = (TextView) view.findViewById(R.id.footer);

clickTextView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getActivity(), "I just clicked my textview!",Toast.LENGTH_LONG).show();
    }
});

xml.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- not selected has transparent color -->
    <item android:state_pressed="false" android:state_selected="false">
        <color android:color="#D8000000"/>
    </item>
    <item android:state_pressed="true" >
        <color android:color="#ff0000"/>
    </item>
    <item android:state_pressed="false" android:state_selected="true">
        <color android:color="#ff0000"/>
    </item>
</selector>

选择后我应该更改什么以使其保持红色。

您可以使用 switch case 语句实现此目的。

首先将 onClick 侦听器添加到您的 TextViews

mQuickReturnView = (TextView) view.findViewById(R.id.footer);
mQuickReturnView1 = (TextView) view.findViewById(R.id.footer1);
mQuickReturnView2 = (TextView) view.findViewById(R.id.footer2);

mQuickReturnView.setOnClickListner(this);
mQuickReturnView1.setOnClickListner(this);
mQuickReturnView2.setOnClickListner(this);

然后像下面这样实现onClick方法。

@Override
public void onClick(View v) {
    switch(v.getId()){
        /*First TextView was clicked, set it as your clicked color and 
          the others as your default, non-clicked color. */
        case R.id.footer:
            mQuickReturnView.setBackgroundColor(Color.GREEN); 
            mQuickReturnView1.setBackgroundColor(Color.BLACK); 
            mQuickReturnView2.setBackgroundColor(Color.BLACK)); 
        break;

        /*Second TextView was clicked, set it as your clicked color and 
          the others as your default, non-clicked color. */
        case R.id.footer1:
            mQuickReturnView.setBackgroundColor(Color.BLACK); 
            mQuickReturnView1.setBackgroundColor(Color.GREEN); 
            mQuickReturnView2.setBackgroundColor(Color.BLACK); 
        break;

        /*Third TextView was clicked, set it as your clicked color and 
          the others as your default, non-clicked color. */
        case R.id.footer2:
            mQuickReturnView.setBackgroundColor(Color.BLACK); 
            mQuickReturnView1.setBackgroundColor(Color.BLACK); 
            mQuickReturnView2.setBackgroundColor(Color.GREEN); 
        break;
    } 
}