在Android中以编程方式选择项目ListView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10788688/
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
Programmatically select item ListView in Android
提问by Jecimi
I have two fragments. The first with buttons inside, the other with a ListView
inside (ListFragment).
我有两个片段。第一个里面有按钮,另一个ListView
里面有一个(ListFragment)。
I would like the first fragment (thanks to its buttons) to allow the user to browse the ListView which is in the second fragment.
我希望第一个片段(由于它的按钮)允许用户浏览第二个片段中的 ListView。
So I want the ListView to be controlled by the first fragment with buttons.
所以我希望 ListView 由第一个带有按钮的片段控制。
I've no problem communicating between fragment (sending orders from 1st fragment to the 2nd), but I don't know how to tell my ListView to select (programmatically) a particular list item.
我在片段之间进行通信没有问题(从第一个片段向第二个片段发送订单),但我不知道如何告诉我的 ListView 选择(以编程方式)特定的列表项。
What kind of ListView should I use and how can I tell the ListView to Select/Highlight/Focus one of its items?
我应该使用哪种 ListView 以及如何告诉 ListView 选择/突出显示/聚焦其中一个项目?
I am in touch mode as the user presses on the buttons of the 1st fragment.
当用户按下第一个片段的按钮时,我处于触摸模式。
Should I use setFocusableInTouchMode(true)
or setChoiceMode(ListView.CHOICE_MODE_SINGLE)
or something else?
我应该使用setFocusableInTouchMode(true)
或setChoiceMode(ListView.CHOICE_MODE_SINGLE)
或其他什么?
回答by Jecimi
This is for everyone trying to :
这是为每个人都试图:
-Select programmatically an Item in a ListView
- 以编程方式在 ListView 中选择一个项目
-Making this Item stay Highlighted
-使此项目保持突出显示
I'm working on Android ICS, I don't know if it works for all levels Api.
我正在研究 Android ICS,我不知道它是否适用于所有级别的 Api。
First create a listview (or get it if you're already in a listActivity/listFragment)
首先创建一个列表视图(如果您已经在 listActivity/listFragment 中,则获取它)
Then set the choice mode of your listview to singlewith :Mylistview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
然后使用以下命令将列表视图的选择模式设置为单一模式:Mylistview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Then select programmatically your itemwith :Mylistview.setItemChecked(position, true);
(position being an integer indicating the rank of the item to select)
然后以编程方式选择您的项目:(Mylistview.setItemChecked(position, true);
位置是一个整数,表示要选择的项目的等级)
Now your item is actually selected but you might see absolutely nothing because there's no visual feedback of the selection. Now you have two option : you can either use a prebuilt listview or your custom listview.
现在您的项目实际上已被选中,但您可能什么也看不到,因为没有选择的视觉反馈。现在您有两个选择:您可以使用预构建的列表视图或自定义列表视图。
1)If you want a prebuilt listview, give a try to simple_list_item_activated_1
, simple_list_item_checked
, simple_list_item_single_choice
, etc...
1)如果你想有一个预置的列表视图,给一个尝试simple_list_item_activated_1
,simple_list_item_checked
,simple_list_item_single_choice
,等...
You can set up your listview like this for e.g : setListAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_activated_1, data))
您可以像这样设置您的列表视图,例如: setListAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_activated_1, data))
following which prebuilt listview you chose you'll see now that when selected you have a checkbox ticked or the backgound color changed , etc...
在您选择的预建列表视图之后,您现在会看到,选择后您会勾选一个复选框或背景颜色已更改,等等...
2)If you use a custom listview then you'll define a custom layout that will be used in each item. In this XML layout you will attribute a selector for each part view in you row which need to be changed when selected.
2)如果您使用自定义列表视图,那么您将定义将在每个项目中使用的自定义布局。在此 XML 布局中,您将为行中的每个部件视图分配一个选择器,选择时需要更改。
Let's say that when selected you want your row to change the color of the text and the color of the background. Your XML layout can be written like :
假设选中后,您希望行更改文本颜色和背景颜色。你的 XML 布局可以这样写:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/menu_item_background_selector"
android:orientation="horizontal" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="@drawable/menu_item_text_selector" />
Now, in the drawable folder you create menu_item_background_selector.xml and menu_item_text_selector.xml.
现在,在 drawable 文件夹中创建 menu_item_background_selector.xml 和 menu_item_text_selector.xml。
menu_item_text_selector.xml :
menu_item_text_selector.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:color="#FFF">
</item>
<item android:state_pressed="true"
android:color="#FFF">
</item>
<item android:state_pressed="false"
android:color="#000">
</item>
</selector>
The text will be white when selected.
选中时,文本将为白色。
Then do something similar for your background: (remember that you're not forced to use color but you can also use drawables)
然后为您的背景做一些类似的事情:(请记住,您不是被迫使用颜色,但您也可以使用可绘制对象)
menu_item_background_selector.xml :
menu_item_background_selector.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:color="#0094CE">
</item>
<item android:state_pressed="true"
android:color="#0094CE">
</item>
<item android:state_pressed="false"
android:color="#ACD52B">
</item>
</selector>
Here the background is blue when selected and green when it is not selected.
此处背景在选中时为蓝色,未选中时为绿色。
The main element I was missing was android:state_activated
. There's indeed (too) many states : activated,pressed,focused,checked,selected...
我缺少的主要元素是android:state_activated
. 确实有(太多)状态:激活、按下、聚焦、检查、选择......
I'm not sure if the exemple I gave with android:state_activated
and android:state_pressed
is the best and cleanest one but it seems to work for me.
我不知道如果我给与为例android:state_activated
并且android:state_pressed
是最好的和最干净的一个,但它似乎为我工作。
But I didn't need to make my own class in order to get a Custom CheckableRelativeLayout(which was dirty and scary) nor I used CheckableTextViews. I don't know whyothers used such methods, it maybe depends on the Api level.
但是我不需要创建自己的类来获得自定义 CheckableRelativeLayout(它既脏又可怕),也不需要使用 CheckableTextViews。我不知道为什么其他人使用这种方法,这可能取决于 Api 级别。
回答by AlikElzin-kilaka
Try AbsListView.performItemClick(...)
试试AbsListView.performItemClick(...)
See this poston how to use performItemClick
.
见这个职位上如何使用performItemClick
。
回答by Axel
This is what worked for me:
这对我有用:
1) Set the choice behavior for the List.
1) 设置列表的选择行为。
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2) Sets the checked state of the specified position.
2) 设置指定位置的选中状态。
mListView.setItemChecked(1,true); //Don't make the same mistake I did by calling this function before setting the listview adapter.
3) Add a new style inside the style resource (res/values) like this:
3)在样式资源(res/values)中添加一个新样式,如下所示:
<style name="activated" parent="android:Theme.Holo">
<item name="android:background">@android:color/holo_green_light</item>
</style>
Feel free to use whichever colours you like.
随意使用您喜欢的任何颜色。
4) Use the previously defined stylein your ListView:
4)在 ListView 中使用之前定义的样式:
<ListView
android:id="@+id/listview"
style="@style/activated"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"/>
Or in the layout you use as row.
或者在您用作行的布局中。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/activated"
>
<!--widgets for your row here-->
</LinearLayout>
Hope that helps anyone!
希望能帮助到任何人!
回答by J_D
Try mListView.setSelection(position);
尝试 mListView.setSelection(position);
回答by Swapnil Chaudhari
Jecimi's answer worked for me except for small part. I would like to share it for others. Calling list.setItemChecked( 0, true );
in onCreate() of FragmentActivity did not work. In getView()
of adapter list.getCheckedItemPosition( )
returned -1.
Jecimi 的回答对我有用,除了一小部分。我想分享给其他人。调用list.setItemChecked( 0, true );
FragmentActivity 的 onCreate() 不起作用。在getView()
适配器list.getCheckedItemPosition( )
返回-1。
I have to call this method from protected void onPostCreate( Bundle savedInstanceState )
.
我必须从protected void onPostCreate( Bundle savedInstanceState )
.
回答by Hasid Mansoori
package com.example.samsung;
import com.example.samsung.*;
import com.example.samsung.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class Firstscreen extends Activity implements OnItemSelectedListener {
Button btn;
Spinner sp;
public String[] product = { "ML-1676P/XIP","SLM2021W/XIP","SL-M2826ND/XIP","SL-M2826ND/XIP","SL-M2826ND/XIP","SL-M3320ND/XIP","SL-M3820ND/XIP","SL-M4020ND/XIP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstscreen);
btn = (Button) findViewById(R.id.bn);
sp= (Spinner) findViewById(R.id.sp);
}
public void button (View v){
{
Intent i = new Intent(Firstscreen.this,ML1676P.class);
startActivity(i);
}
Spinner s1 = (Spinner) findViewById(R.id.sp);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, product); // find other layout parameters
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private Object product() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.firstscreen, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Firstscreen"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF35B5E5"
android:layout_centerInParent="true"
android:text="CHOOSE THE PRODUCT FROM THE LIST" />
<Spinner
android:id="@+id/sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:drawSelectorOnTop="true" />
<Button
android:id="@+id/bn"
android:layout_width="285dp"
android:layout_height="wrap_content"
android:text=" GO "
android:onClick="button"/>
</LinearLayout>
select an item in a listview it should go to the specific selected item page when button is clicked how to do it.The code is snippet above
在列表视图中选择一个项目,当单击按钮时,它应该转到特定的选定项目页面怎么做。代码是上面的片段
回答by Faisal Shaikh
I do like this:
我喜欢这样:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
try {
int pos = 0;
listview.performItemClick(null, pos, listview.getItemIdAtPosition(pos) );
} catch (Exception e) {
e.printStackTrace();
}
}
}
回答by asenovm
You can use ListView#setSelection(int)
您可以使用 ListView#setSelection(int)
回答by zibetto
Just add the following line to the layout of your custom listview:
只需将以下行添加到自定义列表视图的布局中:
android:background="?android:attr/activatedBackgroundIndicator"
For a full working example see:
有关完整的工作示例,请参阅: