Android开发经验总结篇

ColorSelector 和 DrawableSelector

2018-03-20  本文已影响0人  zhengLH

【背景】使用Selector改变TextView的字体颜色textColor的方法

【xml 布局】

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">

<TextView
    android:id="@+id/tv_selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="测试selector"
    android:layout_marginTop="@dimen/margin_20dp"
    android:textSize="@dimen/textSize_22sp"
    android:textColor="@color/test_selector"/>

  </LinearLayout>

【selector 文件】

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:color="@color/colorTheme" android:state_pressed="true"/>
<item android:color="@color/colorTheme" android:state_focused="true"/>
<item android:color="@color/colorTheme" android:state_selected="true"/>
<item android:color ="@color/colorPrimary" android:state_pressed="false"/>

</selector>

【注】有人可能会发现这个selector文件和我们平时在Drawable里面看到的不一样,因为在drawable文件夹中的selector,是不能有android:color属性的,这个文件其实是放在res/color文件夹中的;
所以,对android:textColor赋值时,不是@drawable/xxxxx,而是@color/XXXXX

【结构图】


文件位置图.png

【调用】

 /**
 * @Author Lee
 * @Time 2018/3/19
 * @Theme  测试 drawableSeletor 和 ColorSelector 的 区别
 */

public class TestSelectorActilvity extends AppCompatActivity implements View.OnClickListener {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activit_selector);


   //  findViewById(R.id.tv_selector).setOnClickListener(this);
    findViewById(R.id.tv_selector).setClickable(true);   // 应该设置可点击, 否则效果出不来
}

@Override
public void onClick(View view) {

    Toast.makeText(this, "我他妈被点击了", Toast.LENGTH_SHORT).show();
   }
}
上一篇下一篇

猜你喜欢

热点阅读