user3203425
user3203425

Reputation: 3059

Make TextView bold using selector

When the user presses my textview, I'd like to make the textview bold. This is what I'm trying:

// styles.xml
<style name="TextOn">
    <item name="android:textStyle">bold</item>  
</style>

<style name="TextOff">
    <item name="android:textStyle">normal</item> 
</style>


// my_selector.xml
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:state_pressed="true" style="@style/TextOn" />
  <item android:state_focused="false" android:state_pressed="true" style="@style/TextOn" />
  <item android:state_focused="true" style="@style/TextOn" />
  <item android:state_focused="false" android:state_pressed="false" style="@style/TextOff" />
</selector>


// my textview in a layout
<TextView
  ...
  android:duplicateParentState="true"
  android:textAppearance="@drawable/my_selector" />

Setting textAppearance to a selector drawable doesn't seem right, and in fact, it has no effect. How do we do this?

Thanks

Upvotes: 1

Views: 8021

Answers (3)

Carlos J
Carlos J

Reputation: 3045

As olele said, you can only get a selector to work with colors and drawables, however, you can "make" your own selector in code by making the TextView clickable and intercepting the touch events on the code.

Something like this is proven to work:

    TextView myTextView = (TextView) findViewById(R.id.my_text_view);
    myTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                // When the user clicks the TextView
                case MotionEvent.ACTION_DOWN:
                    mSwitchLayoutButton.setTypeface(Typeface.DEFAULT_BOLD);
                    break;

                // When the user releases the TextView
                case MotionEvent.ACTION_UP:
                    mSwitchLayoutButton.setTypeface(Typeface.DEFAULT);
                    break;
            }
            return false;
        }
    });

Upvotes: 1

olele
olele

Reputation: 69

Applying a selector to a style only works with colors and drawables. Please see the answer in the post below.

How to define bold in an Android selector

Upvotes: 1

pandre
pandre

Reputation: 6725

"Selector works only for drawables, not text appearances. There is currently not plan to make this happen." More Info

Upvotes: 0

Related Questions