我有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>
一旦选择,我应该更改为保持红色。
答案 0 :(得分:1)
您可以使用switch case
语句来实现此目的。
首先将onClick侦听器添加到TextView
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;
}
}