【问题标题】:Android setSelection(index) ListView with HeaderView sets 1 less index带有 HeaderView 的 Android setSelection(index) ListView 设置少 1 个索引
【发布时间】:2012-11-06 17:41:15
【问题描述】:

HeaderView 有 ListView,当我使用 setSelection API 设置索引时,它会将错误(少 1 个)索引设置为选定索引。

以下是代码片段:

final ListView lst = (ListView)findViewById(R.id.listView1);
LinearLayout headerLayout = new LinearLayout(this);
headerLayout.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT,ListView.LayoutParams.WRAP_CONTENT));
headerLayout.setId(9);
lst.addHeaderView(headerLayout, null, false);'code'

例如

listView.setSelection(6);

Button btn6 = (Button)findViewById(R.id.button6);
        btn6.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {

                lst.setSelection(6);
                View v1 = lst.getChildAt(0);
                int top = (v1 == null) ? 0 : v1.getTop();
                lst.setSelectionFromTop(6, top);    

                //lst.setSelection(6);

            }});

这会将焦点设置为 第 5 个位置 项作为选定项。

我试过了

View v1 = listView.getChildAt(0);
View n = lst.findViewById(9); // 9 is id of listView's header.
listView.setSelectionFromTop(6, n.getMeasuredHeight());

View v1 = listView.getChildAt(0);
int top = (v1 == null) ? 0 : v1.getTop();
listView.setSelectionFromTop(6, top);

但这也行不通。

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    试试这个 int index = 6(this can be any number or value) + 1

    listView.setSelection(index);
    View v1 = listView.getChildAt(0);
    int top = (v1 == null) ? 0 : v1.getTop();
    listView.setSelectionFromTop(index, n.getMeasuredHeight());
    

    【讨论】:

    • 我不想硬编码“+1”,有什么替代方法吗?
    • 可能是标题也被添加为一个项目,这就是为什么你必须这样,尝试删除标题并查看
    • 我想只用 HeaderView 来实现这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多