Programmatically select ListView item in Android

I have two fragments. The first with buttons inside, the other with ListView inside (ListFragment).

I would like the first fragment (thanks to its buttons) to allow the user to view the ListView, which is in the second fragment.

So, I want the ListView to be controlled by the first fragment using buttons.

I have no problems communicating between the fragment (sending orders from the 1st fragment to the 2nd), but I do not know how to let my ListView select (programmatically) a specific list item.

What kind of ListView should I use and how can I show the ListView to select / select / focus one of its elements?

I am in touch mode when the user clicks on the buttons of the 1st fragment.

Should I use setFocusableInTouchMode(true) or setChoiceMode(ListView.CHOICE_MODE_SINGLE) or something else?

+44
android listview highlight
May 28 '12 at 17:57
source share
9 answers

This is for everyone trying:

- Programmatically select an item in a ListView

- The stay of this stay element is highlighted

I am working on Android ICS, I do not know if it works at all levels of Api.

First create a listview (or get one if you are already in the Activity / listFragment list)

Then set your list selection mode to single using: Mylistview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

Then programmatically select your item using Mylistview.setItemChecked(position, true); (the position is an integer indicating the rank of the item to select)

Now your item is actually selected, but you can see absolutely nothing, because there is no visual feedback of the choice. Now you have two options: you can use a pre-built list or your own list.

1) If you want to create a pre-created list, try simple_list_item_activated_1 , simple_list_item_checked , simple_list_item_single_choice , etc.

You can customize your list this way, for example: setListAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item_activated_1, data))

after which you have selected a pre-configured list, you will see that when you select the checkbox, the checkbox is checked or the background has changed, etc.

2) If you use a custom list, you will define a custom layout that will be used in each element. In this XML layout, you assign a selector to each type of part in the row that you want to change when you select it.

Suppose that when you select, you want your line to change the text color and background color. Your XML layout can be written as follows:

 <?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 drop-down folder you will create menu_item_background_selector.xml and 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> 

When you select text, the text will be white.

Then do something similar for your background: (remember that you are not forced to use color, but you can also use drawables)

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 blue background, if selected, and green, if not selected.

The main element that I was missing was android:state_activated . There really are (also) many states: activated, pressed, focused, checked, selected ...

I'm not sure if the example I gave with android:state_activated and android:state_pressed is the best and cleanest, but it seems to work for me.

But I didn't need to create my own class to get Custom CheckableRelativeLayout (which was dirty and scary), and I did not use CheckableTextViews. I don’t know why others used such methods, maybe it depends on the level of Api.

+127
May 28 '12 at 23:05
source share

Try AbsListView.performItemClick (...)

See this post on how to use performItemClick .

+14
Apr 22 '13 at 11:54 on
source share

This is what worked for me:

1) Define the selection behavior for the list.

  mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

2) Sets the checked state of the specified position.

 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 to the style resource (res / values) as follows:

 <style name="activated" parent="android:Theme.Holo"> <item name="android:background">@android:color/holo_green_light</item> </style> 

Feel free to use any colors you like.

4) Use a previously defined style in 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 that you use as a string.

 <?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 someone helps!

+6
Oct 17 '15 at 5:48
source share

Jecimi's answer worked for me, with the exception of a small part. I would like to share it with others. Call list.setItemChecked( 0, true ); in onCreate (), the FragmentActivity function does not work. Returns -1 in the getView() adapter.

I need to call this method from protected void onPostCreate( Bundle savedInstanceState ) .

+4
Dec 24 '14 at 6:20
source share

Try mListView.setSelection(position);

+3
May 28 '12 at 18:00
source share

You can use ListView#setSelection(int)

0
May 28 '12 at 17:59
source share
 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 the list, it should go to a specific page of the selected item when the button is pressed how to do it. The code is a snippet above

0
Nov 07 '15 at 5:07
source share

I like the following:

 @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(); } } } 
0
Aug 04 '16 at 11:01
source share

Just add the following line to your custom list layout:

 android:background="?android:attr/activatedBackgroundIndicator" 

For a complete working example, see

https: //elimelec@bitbucket.org/elimelec/custombaseadapter.git

-one
Jul 12 '14 at 2:17
source share



All Articles