ListView没有通知

时间:2014-08-14 04:10:11

标签: android listview notify

我在自定义导航抽屉中使用列表片段。我想在按下时更改列表项中文本视图的颜色。我将项目点击位置传递给适配器并通知适配器。但它没有用。但是当我再次设置适配器时,它正在工作。但运动并不顺利。我该怎么做才能克服这个问题?

以下是片段的Lis​​tItem点击,

@Override
public void onListItemClick(ListView lView, View v, final int position, long id) {
    super.onListItemClick(lView, v, position, id);
    adapter.setSelectedIndex(position);
    adapter.notifyDataSetChanged();
    lView.setAdapter(adapter);
}

并且适配器具有以下代码,

public void setSelectedIndex(int ind)
{

    selectedIndex = ind;
    notifyDataSetChanged();
}

我的onactivity已创建

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    menuitemlist=new ArrayList<MenuItem>();
    menuitemlist.clear();
    for(int i=0;i<menulist.length;i++){
        MenuItem item=new MenuItem();
        item.icon=iconlist[i];
        item.menuText=menulist[i];
        item.status=0;
        menuitemlist.add(item);
    }

    adapter=SlidingListAdapter.newInstance(myActivity, menuitemlist);       
    setListAdapter(adapter);

}

1 个答案:

答案 0 :(得分:2)

方法1

Set your list adapter outside `onListItemClick()`

    lView.setAdapter(adapter);

    @Override
    public void onListItemClick(ListView lView, View v, final int position, long id) {
        super.onListItemClick(lView, v, position, id);
        adapter.setSelectedIndex(position);
        adapter.notifyDataSetChanged();
    }

方法2

View lastSelectedView = null;

@Override
public void onListItemClick(ListView lView, View v, final int position, long id) {
    super.onListItemClick(lView, v, position, id);
    if(lastSelectedView != null){
      TextView txtView = (TextView)lastSelectedView.findViewById(R.id.x);
      txtView.setTextColor(defaultColor);
    }
    TextView txtView = (TextView) v.findViewById(R.id.x);
    txtView.setTextColor(pressedColor);

    lastSelectedView = v;
}

方法3

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:color="#ff0000"/>
    <item android:state_selected="true" android:color="#00ff00"/>
    <item android:color="#000000"/>

</selector>

并将此选择器文件设置为TextView的TextColor