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
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:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With