简体   繁体   中英

Change textview color on selected

What I need is that the color of the TextView changes to red when clicked/tapped but when I don't tap it anymore it has to go back to white, the original color.

Here's my .xml:

    <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/vu"
android:id="@+id/textView"
android:gravity="center"
android:textSize="60sp"
android:textColor="#ffffff"
android:background="#212121"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

Here's my .java:

public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    TextView tv = (TextView) findViewById(R.id.textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Light.ttf");
    tv.setTypeface(typeface);
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("http://www.papery.hol.es");
    webView.setWebViewClient(new WebViewClient());
    webView.setVerticalScrollBarEnabled(false);
    webView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    // Look up the AdView as a resource and load a request.
    AdView adView = (AdView) this.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    }
}

Create a color state list resource in your /res/color/ folder, like this:

/res/color/text_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#ff0000" />
    <item android:color="@android:color/white"/>
</selector>

Then use this resource as your text color:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:textColor="@color/text_color"
    android:clickable="true"
    />

Note that for this to work, you either have to set the android:clickable attribute to true or set a click listener on your textview in code.

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