سؤال

I'm trying to change the background of a textview when clicked.

For instance, if the textview is click it the background changes to yellow and remains yellow until it is click again. Then it returns to its default background.

Currently textview the background changes on pressed down, but returns to default on release.

I have search the internet for solutions and look at most of all the solution on stackoverflow, still no solution.

Drawable/selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/circle_on" android:state_enabled="true" android:state_pressed="true"/>
     <item android:drawable="@drawable/circle_on" android:state_enabled="true" android:state_focused="true"/>
     <item android:drawable="@drawable/circle_off"/>
</selector>

Drawable/circle_on:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval" >
   <stroke
     android:width="2dp"
     android:color="@color/Gray" >
   </stroke>
   <solid android:color="@color/LightBlue" />
</shape>

Drawable/circle_off:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval" >
    <stroke
        android:width="2dp"
        android:color="@color/Gray" >
    </stroke>
    <solid android:color="@color/WhiteSmoke" />
</shape>

TextView:

  <TextView
                style="@style/RoundText"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@drawable/repeat_selector"
                android:clickable="true"
                android:text="Sun" >
            </TextView>

Text Style:

  <style name="RoundText">
    <item name="android:textColor">#555555</item>
    <item name="android:gravity">center_vertical|center_horizontal</item>
    <item name="android:textSize">15sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:fontFamily">sans-serif-thin</item>
</style>

Can someone please tell me what I'm doing wrong

Thanks.

MY Solution:

    public class PlanTextView extends TextView  {

private boolean _stateChanged;
private boolean _selected;

public boolean is_stateChanged() {
    return _stateChanged;
}

public void set_stateChanged(boolean _stateChanged) {
    this._stateChanged = _stateChanged;
}

public boolean is_selected() {
    return _selected;
}

public void set_selected(boolean _selected) {
    this._selected = _selected;
}

public PlanTextView(Context context) {
    super(context);
}

public PlanTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public PlanTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
 }


<com.plan.views.PlanTextView
                android:id="@+id/mon"
                style="@style/RoundText"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@drawable/circle_off"
                android:clickable="true"
                android:onClick="PlanOnClick"
                android:text="mon" >
 </com.plan.views.PlanTextView>

Activity

public void PlanOnClick(View v) {
    PlanTextView view = (PlanTextView)v;
    if (view.is_stateChanged()) {
        view.setBackgroundResource(R.drawable.circle_off);
        view.set_selected(false);
    } else {
        view.setBackgroundResource(R.drawable.circle_on);
        view.set_selected(true);
    }
    view.set_stateChanged(!view.is_stateChanged());
}
هل كانت مفيدة؟

المحلول 2

If the textview is clicked the background changes to yellow and remains yellow until it is click again. Then it returns to its default background.

It's a matter of logic as you need to keep in your click listener the current click state.(blind coding):

textView.setOnClickClickListener(new View.OnClickListener() {
    private boolean stateChanged;
    public void onClick(View view) {
        if(stateChanged) {
            // reset background to default;
            textView.setBackgroundDrawable(circleOffDrawable);
        } else {
            textView.setBackgroundDrawable(circleOnDrawable);
        }
        stateChanged = !stateChanged;
    }
});

To improve the answer, you should keep stateChanged flag in the activity and retain its value across activity recreations - if the user rotates the activity. (Store the flag in onSaveInstanceState and restore in onCreate if its parameter is not null.)

نصائح أخرى

Apart from the above answers,try this code snippet too.

 <selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
      <shape>
        <gradient android:endColor="#AD1F2D" android:startColor="#AD1F2D" />
      </shape>
    </item>
    <item android:state_focused="true">
      <shape>
        <gradient android:endColor="#ff4b46" android:startColor="#ff4b46" />
      </shape>
    </item>
    <item>
      <shape>
        <gradient android:endColor="#ff4b46" android:startColor="#ff4b46" />
      </shape>
    </item>

</selector>

I hope this will useful for everyone.

use a onclicklistner() for your Textview

In your listener use

      txt.setBackgroundColor(Color.RED); 

For example

    if(count==1)
    {
      txt.setBackgroundColor(Color.YELLOW); 
      count=0;
      } 
       else
    if(count==0)
      { 
         txt.setBackgroundColor(Color.RED); 
       count==1;
          }

In the onCreate() method,

LinearLayout(or Whatever layout you are using) ll = (LinearLayout)findViewById(R.id.mainlay);

and set the listener on textview:

TextView tv1 = (TextView)findViewById(R.id.maintext);

tv1.setOnClickListener(this);

And finally on click:

@Override
public void onClick(View v) {

ll.setBackgroundColor(whatever color);
or If you want to change the text background color,

tv1.setBackground(whatevercolor);

}

Hope this helps.

In case anyone needs it (Kotlin). This can toggle TextView's background and text color on click.

ToggleTextView.kt

class ToggleTextView : AppCompatTextView {
    private var mfilterSelected = false
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int): super(context, attrs, defStyle) {}`

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, checkableId: Int) : super(context) {}

    constructor(context: Context) : super(context) {}

    fun isFilterSelected(): Boolean {
        return mfilterSelected
    }

    fun toggleFilterState() {
        if (mfilterSelected) {
            background = resources.getDrawable(R.drawable.toggle_1)
            setTextColor(resources.getColor(R.color.gray))
            mfilterSelected = false
        } else {
            background = resources.getDrawable(R.drawable.toggle_2)
            setTextColor(resources.getColor(R.color.white))
            mfilterSelected = true
        }
    }
}

--toggle_1.xml--
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<stroke android:width="1dp" android:color="@color/gray" />
<corners android:radius="10dp" />
<solid android:color="@color/white" />
</shape>
--toggle_2.xml--
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners android:radius="10dp" />
<solid android:color="@color/orange" />
</shape>
Click listener in your Activity/Fragment:
yourTextView?.setOnClickListener {
            yourTextView.toggleFilterState()
        }
Usage in our xml layout file:
<ToggleTextView
                android:id="@+id/yourTextView"
                android:background="@drawable/toggle_1"
                android:clickable="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:lines="1"/>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top