安卓:自定义相册setSelection()问题

4

我有一个扩展了BaseAdapter的类,其中包含LinearLayout子项(每个子项中都包含一个ImageView和一个TextView),这些子项连接到一个自定义的Gallery。

当我首次启动我的Activity时,我想调用setSelection(position)方法,以使ImageView更改其选择器为“selected”图像。 这在我滑动Gallery后的选定子项上有效,但不适用于应用程序首次启动时的第一次选定子项。

我的选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" 
    android:drawable="@drawable/home_image_select" /> 
<item android:state_selected="false" 
    android:drawable="@drawable/home_image" /> 
</selector>

我的第一个猜测是在调用setSelection()后在适配器上调用notifyDataSetChanged(),我尝试像这样做:

((CustomAdapter) gallery.getAdapter()).notifyDataSetChanged();

那并没有起到任何作用。我还试图覆盖Gallery类的setSelection()方法来实现这一点:

View v = this.getAdapter().getView(position, null, this);       
((ImageView) v.findViewById(R.id.gallery_image)).setSelected(true);

那也不起作用。我有什么遗漏或可以尝试的吗?
2个回答

0

我通过重写Gallery的setSelection()方法找到了解决自己问题的方法(结果还真奏效了)。

 @Override
public void setSelection(int position) {
    super.setSelection(position);

    View v = this.getAdapter().getView(position, null, this);
    v.setFocusable(true);
    v.requestFocus();
}

0

我认为你不应该调用notifyDataSetChanged(),因为当基础数据集改变时,选择状态会被清除。

只需在我的应用中调用setSelection(position)即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接