美文网首页
TextView实现类似checkbox选择状态

TextView实现类似checkbox选择状态

作者: Y小圆脸 | 来源:发表于2017-09-18 13:56 被阅读261次

1、TextView实现类似checkbox选择状态

package com.shoushan.zhenxin.view;


import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.Checkable;

public class CheckableTextView extends android.support.v7.widget.AppCompatTextView implements Checkable {

private boolean mChecked;

private static final int[] CHECKED_STATE_SET = {
        android.R.attr.state_checked
};

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

public CheckableTextView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected int[] onCreateDrawableState(int extraSpace) {
    final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
    if (isChecked()) {
        mergeDrawableStates(drawableState, CHECKED_STATE_SET);
    }
    return drawableState;
}

@Override
public void setChecked(boolean checked) {
    mChecked = checked;
    refreshDrawableState();
}

@Override
public boolean isChecked() {
    return mChecked;
}

@Override
public void toggle() {
    mChecked = !mChecked;
}
}

2、在xml中引用,

 <com.shoushan.zhenxin.view.CheckableTextView
    android:id="@+id/ctv_show"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp"
    android:drawablePadding="10dp"
    android:drawableRight="@drawable/selector_client_status"
    android:gravity="center"
    android:text="收起"
    android:textColor="@color/color_f6aO2f"
    android:textSize="14dp" />

3、Selector相关

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/icon_pack_up" android:state_checked="true" />
     <item android:drawable="@drawable/icon_pack_down" android:state_checked="false" />
</selector>

JAVA代码中只需要简单setChecked调用就实现了

相关文章

网友评论

      本文标题:TextView实现类似checkbox选择状态

      本文链接:https://www.haomeiwen.com/subject/owqbsxtx.html