要达到这个效果需要用到 setOnFocusChangeListener 监听方法。代码如下:
ListView的xml布局:
<ListView
android:id="@+id/a_listbody_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@null" >
</ListView>
ListView的item布局:
<?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:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/lt_height126"
android:gravity="center_vertical"
android:paddingLeft="@dimen/default_grap45" >
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/font_text16" />
</LinearLayout>
</LinearLayout>
布局文件就这样,很简单吧!
下面看看核心代码:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder holder = null;
// if (convertView == null) {
// holder = new ViewHolder();
convertView = getLayoutInflater().inflate(
R.layout.item_communityaddr_layout, null);
convertView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
v.setBackgroundColor(R.color.bg_orange);
}
});
TextView mTextName = (TextView) convertView.findViewById(R.id.item_text);
// holder.mTextName = (TextView) convertView
// .findViewById(R.id.item_text);
// convertView.setTag(holder);
// } else {
// holder = (ViewHolder) convertView.getTag();
// }
监听每个item(convertView)的焦点获取情况。当该item获取到焦点时 就是设置其背景颜色。这样就达到我们的效果啦!是不是很简单呢?