android 机顶盒 listview 获取焦点改变item背景

来源:互联网 发布:mac口红官网价格多少 编辑:程序博客网 时间:2024/05/20 18:48
在网上搜索了很多文章都没有找到我想要的效果。 正所谓实践才是真理,于是我反复猜测和调试,最终达到了我想要的效果!下面分享代码,希望能帮助到需要的人!

要达到这个效果需要用到 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获取到焦点时 就是设置其背景颜色。这样就达到我们的效果啦!是不是很简单呢?

0 0