建立選擇器實作圓角矩形
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="5dip"/>
<solid android:color="#33ff0000"/>
</shape>
建立選擇器實作字型顔色改變
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true" android:color="@android:color/white"></item>
<item android:state_pressed="true" android:color="@android:color/white"></item>
<item android:color="@android:color/darker_gray"></item>
</selector>
建立選擇器實作背景顔色改變
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true" android:drawable="@drawable/bgshape_shape"></item>
<item android:state_pressed="true" android:drawable="@drawable/bgshape_shape"></item>
</selector>
布局檔案引用
<TextView
android:layout_width="80dip"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@drawable/textcolor_selector"
android:background="@drawable/bgcolor_selector"
android:padding="5dip"
android:text="熱門" />
MainActivity背景代碼實作
private int screenWitdth;
private HorizontalScrollView hsv;
private LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲得螢幕寬度
screenWitdth = getResources().getDisplayMetrics().widthPixels;
//初始化視圖
initView();
//子控件點選事件
initEvent();
}
//初始化視圖
private void initView(){
hsv = (HorizontalScrollView) findViewById(R.id.hsv);
ll = (LinearLayout) findViewById(R.id.ll);
//預設選中第一個子控件
hsv.getChildAt().setSelected(true);
}
//定義子控件點選事件
private void initEvent(){
//獲得水準滑動控件中子控件——水準線性布局内共有多少子控件
int childrenCount=hsv.getChildCount();
//對子控件循環監聽
for(int i=; i<childrenCount; i++){
final int currentIndex=i;
//獲得目前子控件
View childView=hsv.getChildAt(i);
//對目前子控件設定點選監聽事件
childView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//設定目前子控件诶選中
selectChildView(currentIndex);
}
});
}
}
//對點選選中的子控件進行設定
private void selectChildView(int position){
int childrenCount=hsv.getChildCount();
for(int i=; i<childrenCount; i++){
//獲得目前子控件對象,并設定為選中狀态
View child=hsv.getChildAt(i);
child.setSelected(true);
}
//設定選中條目居中
View currentView=hsv.getChildAt(position);
int left=currentView.getLeft(); //擷取點選控件與父控件左側的距離
int width=currentView.getMeasuredWidth(); //獲得控件本身寬度
int toX=left+width/-screenWitdth/;
//使條目移動到居中顯示
hsv.smoothScrollTo(toX, );
}