Android ListView setSelection() 似乎不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1446373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:06:09  来源:igfitidea点击:

Android ListView setSelection() does not seem to work

androidlistview

提问by alkar

I have a ListActivitythat implements onListItemClick()and calls a doSomething()function of the class. The latter contains l.setSelection(position)where lis the ListViewobject.

我有一个ListActivity实现onListItemClick()并调用doSomething()类的函数。后者包含l.setSelection(position)其中lListView对象。

Now there is a onClickListener()listening for a button click that perfoms some actions and that too calls doSomething().

现在可以onClickListener()监听执行某些操作的按钮单击,并且也调用doSomething().

In the first case, the selected item get positioned appropriately, but in the latter, nothing happens.

在第一种情况下,所选项目得到适当定位,但在后一种情况下,什么也没有发生。

Any clues about this strange behaviour and how I might make it work?

关于这种奇怪行为的任何线索以及我如何使它起作用?

回答by meizilp

maybe you need to use function:

也许你需要使用功能:

ListView.setItemChecked(int position, boolean checked);

回答by AlexD

use requestFocusFromTouch()before calling setSelection()method

requestFocusFromTouch()在调用setSelection()方法之前使用

回答by mr_hyde

I know this is an old question but I just had a similar problem that I solved in this way:

我知道这是一个老问题,但我刚刚遇到了一个类似的问题,我以这种方式解决了:

mListView.clearFocus();
mListView.post(new Runnable() {
    @Override
    public void run() {
        mListView.setSelection(index);
    }
});

回答by kostmo

You might need to wrap setSelection()in a posted Runnable(reference).

您可能需要包含setSelection()posted Runnable( reference) 中。

回答by CommonsWare

setSelection()does not necessarily have visual impact. The selection bar only appears if you use the D-pad/trackball to navigate the list. If you tap on the screen to click something, the selection bar appears briefly and vanishes.

setSelection()不一定有视觉冲击。选择栏仅在您使用方向键/轨迹球导航列表时出现。如果您点击屏幕以单击某些内容,则选择栏会短暂出现并消失。

Hence, setSelection()will only have a visual impact if the activity is not in touch mode (i.e., the last thing the user did was use the D-pad/trackball).

因此,setSelection()只有在活动未处于触摸模式时才会产生视觉影响(即,用户所做的最后一件事是使用方向键/轨迹球)。

I am not 100% certain this explains your phenomenon given the description you provided, but I figured it is worth a shot...

鉴于您提供的描述,我不能 100% 确定这可以解释您的现象,但我认为值得一试......

回答by Bobs

If you use an Adapter for your ListView add this code to your adapter:

如果您为 ListView 使用适配器,请将此代码添加到您的适配器:

public class MyAdapter extends
        ArrayAdapter<MyClass> {


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflator = (LayoutInflater) getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflator.inflate(R.layout.my_adapter, null);
        } else {
            rowView = (View) convertView;
        }

        //...

        // set selected item
        LinearLayout ActiveItem = (LinearLayout) rowView;
        if (position == selectedItem)
        {
            ActiveItem
                    .setBackgroundResource(R.drawable.background_dark_blue);

            // for focus on it
            int top = (ActiveItem == null) ? 0 : ActiveItem.getTop();
            ((ListView) parent).setSelectionFromTop(position, top);
        }
        else
        {
            ActiveItem
                    .setBackgroundResource(R.drawable.border02);
        }

    }

    private int selectedItem;

    public void setSelectedItem(int position) {
        selectedItem = position;
    }

}

In your Activity:

在您的活动中:

myAdapter.setSelectedItem(1);

回答by Nick

I have an very large Request with Webcontent. When I used the code in onCreateView the Listview wasnt even finished loading. I put it in onPostExecute of my AsyncTask.

我有一个非常大的 Webcontent 请求。当我在 onCreateView 中使用代码时,Listview 甚至还没有完成加载。我把它放在我的 AsyncTask 的 onPostExecute 中。

            //Get last position in listview
        if (listView != null && scrollPosition != 0) {
            listView.clearFocus();
            listView.requestFocusFromTouch();
            listView.post(new Runnable() {
                @Override
                public void run() {
                    listView.setItemChecked(scrollPosition, true);
                    listView.setSelection(scrollPosition);
                }
            });
        }

Dont forget to set the item checked in on Click ;)

不要忘记设置在 Click 上签入的项目;)

回答by MaInStReAm

For me calling

给我打电话

listView.notifyDataSetChanged();
listView.requestFocusFromTouch();

and then

进而

 listView.setSelection(position);

solved the issue.

解决了这个问题。

if you do that in a runnable it works without calling requestFocusFromTouch(), but the old position of the ListView is showen for a sekound.

如果您在可运行对象中执行此操作,则无需调用 requestFocusFromTouch() 即可工作,但会显示 ListView 的旧位置以用于 sekound。

回答by TaoZang

Maybe you should use the smoothScrollToPosition(int position) method of ListView

也许你应该使用 ListView 的 smoothScrollToPosition(int position) 方法

回答by Courysky

You can try 2 ways like these:
Solution A:

您可以尝试以下 2 种方法:
解决方案 A:

    mListView.post(new Runnable() {
        @Override
        public void run() {
            if (null != mListView) {
                mListView.clearFocus();
                mListView.requestFocusFromTouch();
                mListView.setSelection(0);
            }
        }
    });

In some complicated situation, this solution will bring some new problems in Android 8.x.
Besides it may cause unexpected onFocusChange().

在一些复杂的情况下,这种解决方案会在Android 8.x 中带来一些新的问题。
此外它可能会导致意外的 onFocusChange()。

Solution B: Define a custom view extends ListView. Override method handleDataChanged().Then setSelection(0). In CustomListView:

方案B:定义一个自定义视图扩展ListView。覆盖方法handleDataChanged().然后setSelection(0)。在自定义列表视图中:

@Override
protected void handleDataChanged() {
    super.handleDataChanged();
    if (null != mHandleDataChangedListener){
        mHandleDataChangedListener.onChanged();
    }
}
HandleDataChangedListener mHandleDataChangedListener;

public void setHandleDataChangedListener(HandleDataChangedListener handleDataChangedListener) {
    this.mHandleDataChangedListener = handleDataChangedListener;
}

public interface HandleDataChangedListener{
    void onChanged();
}

In activity:

在活动中:

    mListView.setHandleDataChangedListener(new CustomListView.HandleDataChangedListener() {
        @Override
        public void onChanged() {
            mListView.setHandleDataChangedListener(null);
            mListView.setSelection(0);
        }
    });
    mAdapter.notifyDataSetChanged();

Ok, That's it.

好的,就是这样。