Skip to content

Instantly share code, notes, and snippets.

@dingzhihu
Last active December 28, 2015 15:28
Show Gist options
  • Save dingzhihu/7521597 to your computer and use it in GitHub Desktop.
Save dingzhihu/7521597 to your computer and use it in GitHub Desktop.
create custom selector
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Foo">
<attr name="state_foo_enabled" format="boolean" />
</declare-styleable>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item app:state_foo_enabled="true">
<color android:color="#F00"/>
</item>
<item>
<color android:color="#00F"/>
</item>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.HelloAndroid.widget.MyTextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:padding="20dp"
android:background="@drawable/bg_selector"
android:text="hello" />
<com.example.HelloAndroid.widget.MyTextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:padding="20dp"
android:background="@drawable/bg_selector"
android:text="hello" />
</LinearLayout>
package com.example.HelloAndroid;
import android.app.Activity;
import android.os.Bundle;
import com.example.HelloAndroid.widget.MyTextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((MyTextView) findViewById(R.id.text2)).setFoo(true);
}
}
package com.example.HelloAndroid.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import com.example.HelloAndroid.R;
/**
* Created with IntelliJ IDEA.
* User: dingzhihu
* Date: 13-11-18
* Time: 上午10:08
*/
public class MyTextView extends TextView {
private static final int[] STATE_FOO_ENABLED = {
R.attr.state_foo_enabled
};
private boolean isFoo;
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setFoo(boolean foo) {
isFoo = foo;
refreshDrawableState();
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isFoo) {
mergeDrawableStates(drawableState, STATE_FOO_ENABLED);
}
return drawableState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment