Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate ListView with text and value from strings.xml

I'm new to android and want to populate listview items that have id as value and string as caption. All I could find searching was that they suggest using string array like:

<string-array name="test">
      <item>first item</item>
      <item>second item</item>
</string-array>

What i'm looking for is something like:

<string-array name="test">
      <item value="1">first item</item>
      <item value="2">second item</item>
</string-array>

just like the option tags of a select in html

like image 693
Ashkan Mobayen Khiabani Avatar asked Aug 18 '16 13:08

Ashkan Mobayen Khiabani


1 Answers

Create a new Activity (this will make a xml file (layout) and a Java class.

On the layout, create a Layot that has a ListView on int:

<?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=”match_parent”
    android:orientation=”vertical” >

 <ListView
    android:id=”@+id/itemList”
    android:layout_width=”match_parent”
    android:layout_height=”wrap_content” 
    android:entries="@array/test"
/>

On your activity, you have to:

  • Create a ListView variable
  • Map your view on the XML on this variable
  • Get a list of Strings from your resource array-adapter
  • Instanciate an Adapter (an object that you have to set on your listview to get your list (in your case, of strings) and add them in your recycler view. You can create a customized class for your adapter it, but when dealing with Strings, you can use a simple one called ArrayAdapter).
  • Set your adapter on your ListView object

To do all of those things, you put this in your code:

public class MyActivity extends Activity {

    // Creating variable
    ListView listView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Mapping with your XML view
        listView = (ListView) findViewById(R.id.itemList);

        /// Getting list of Strings from your resource
        String[] testArray = getResources().getStringArray(R.array.test); 
         List<String> testList = Arrays.asList(test);

        // Instanciating Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(),
    android.R.layout.simple_list_item_1, testList);

        // setting adapter on listview
        listview.setAdapter(adapter);
    }
}
like image 135
Leonardo Sibela Avatar answered Oct 20 '22 10:10

Leonardo Sibela