[英]Focus 1st item in a listview when starting an activity android
I am developing an app that when I press a button ,It starts a new activity (ContactList.java) that contains a listview called mContactList. 我正在开发一个应用程序,当我按下按钮时,它会启动一个新活动(ContactList.java),其中包含一个名为mContactList的列表视图。 When the activity starts I want the first item of the listview to be automatically focused. 活动开始时,我希望列表视图的第一项自动聚焦。
I tried something like that: 我尝试过这样的事情:
ContactList.java ContactList.java
mContactsList.requestFocus(mContactsList.getFirstVisiblePosition());
I have also created this two xml resources to ensure that when the view is focused a rectangle is displayed around the item of the listview: 我还创建了这两个xml资源,以确保在聚焦视图时在listview的项目周围显示一个矩形:
selected_rectangle.xml selected_rectangle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:color="@color/blue"
android:width="5dp"/>
</shape>
selector_contact_list.xml selector_contact_list.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:drawable="@drawable/selected_rectangle"/> </selector>
For some reason this code doesn´t work and I am not able to set focus on the first item of the list (since no rectangle appears around the first item of the list). 由于某种原因,此代码无法正常工作,我无法将注意力集中在列表的第一项上(因为列表的第一项周围没有矩形出现)。
Can someone give me clues what is happening? 有人可以告诉我发生了什么事吗?
Please note that setting focus and setting selection are two different things.. and I think you mean the second one, if so try this: 请注意,设置焦点和设置选择是两件事。.我想您的意思是第二个,如果是这样,请尝试以下操作:
listViewName.setSelection(positionOfItem);
if that didn't work, try requestFocusFromTouch()
before calling setSelection()
method. 如果不起作用,请在调用setSelection()
方法之前尝试requestFocusFromTouch()
。
and if that didn't work, try this: 如果不起作用,请尝试以下操作:
listViewName.setItemChecked(positionOfItem, true);
Or this: 或这个:
listViewName.smoothScrollToPosition(positionOfItem);
For other solutions try the answers in this link: Android ListView setSelection() does not seem to work 对于其他解决方案,请尝试以下链接中的答案: Android ListView setSelection()似乎不起作用
采用
listview.setselection(thenumber/position);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.