带有HeaderView的Android setSelection(index)ListView设置了少1个索引

时间:2012-11-06 08:23:41

标签: android android-listview

ListView带有 HeaderView ,当我使用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'

e.g。

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);

但这也行不通。

1 个答案:

答案 0 :(得分:0)

试试这个 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());