点击或选中ListView中的一项后。使item背景改变,失去焦点相同显示选中的背景。又一次选中另外一项才刷新;
在Adapter中配置:
public class MyAdapter extends BaseAdapter{ int mSelect = 0; //选中项 ...... public void changeSelected(int positon){ //刷新方法 if(positon != mSelect){ mSelect = positon; notifyDataSetChanged(); } }public View getView(int position, View convertView, ViewGroup parent) {// if(convertView==null){ LayoutInflater factory = LayoutInflater.from(context); View v = (View) factory.inflate(R.layout.list_item, null); TextView tv = (TextView) v.findViewById(R.id.Item_tv); tv.setText("test");// } if(mSelect==position){ v.setBackgroundResource(R.drawable.fc_bg); //选中项背景 }else{ v.setBackgroundResource(R.drawable.bg); //其它项背景 } return v; }}
配置好了之后,以下就是应用:
...........mAdapter = new MyAdapter(...);myList.setAdapter(mAdapter);//点击监听myList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { mAdapter.changeSelected(position);//刷新 }......}选中监听myList.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { mAdapter.changeSelected(position);//刷新 }......}
-------------------------------------------------------------------------------------
监听view获得焦点或按下等状态的背景,能够用selector。
在res--drawable中配置样式文件,如button_style.xml
> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/btn_bg_fc" /><!--按下时的背景--> <item android:state_focused="true" android:drawable="@drawable/btn_bg_fc" /><!--获得焦点时的背景--> <item android:state_selected="true" android:drawable="@drawable/btn_bg_fc" /><!--选中状态的背景--> <item android:drawable="@drawable/btn_bg" /> <!--默认背景--> </selector>
用在Listview,gridview中
<ListView
......
android:listSelector="@drawable/button_style"......> </ListView>
用于其它View,如Button,textview等
android:background="@drawable/button_style"