selector是在res/drawable/下配置的xml,可以改变原来控件背景,例如button按下时的效果,对设计有不小帮助。
以button效果为例基本配置如下:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/button_unpressed" />
<item
android:state_pressed="true"
android:drawable="@drawable/button_pressed" />
</selector>
保存成selector_login_gmail.xml
可以通过设置android:state_xxx来配置不同状态下的图片背景
常用的有:
无android:state_xxx的用于设置默认背景
android:state_focused="true" 获取焦点时
android:state_pressed="true" 按下时
android:state_selected="true" 选中时
使用的时候可以对常用控件进行设置,例如用LinearLayout模拟Button
<LinearLayout
android:id="@+id/login_gmail"
android:layout_width="250dp"
android:layout_height="wrap_content"
adnroid:gravity="center_vertical"
android:background="drawable/selector_login_gmail.xml">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:text="@string/login_gmail"
android:color="@color/white"
</LinearLayout>
在Activity中获取点击事件:
public class DoodleplusActivity extends Activity {
ViewHolder mviewHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_doodleplus);
mviewHolder = new ViewHolder();
mviewHolder.login_gmail_btn = (LinearLayout) findViewById(R.id.login_gmail);
onButtonClickListener mbuttonClickListener = new onButtonClickListener();
mviewHolder.login_gmail_btn.setOnClickListener(mbuttonClickLLinearLayout mLayout;istener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.doodleplus, menu);
return true;
}
class onButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.welcome_login_google:
Log.w("OnClick", "login_gmail clicked!");
break;
}
}
}
static class ViewHolder {
LinearLayout login_gmail_btn;
}
}