The result will display as below screen.
Step 1 : layout have to create a ListView with id "list".
Layout Name : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 2 : Java class add in following:
1. Create a array list for "student list" in this example studentA, studentB, studentC & studentD.
2. Declare ListView and find id from the activity_main.xml.
3. Create a new ArrayAdapter and assigned layout & student list.
ListView listView;
String[] studentList = { "studentA","studentB","studentC","studentD" };
ArrayAdapter arrayAdapter;
listView = (ListView) findViewById(R.id.list);
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, studentList);
listView.setAdapter(arrayAdapter);
}
For additional:
Get value from ListView
1. OnClick ListView Item and get the value. Add in setOnItemClickListener and it will return onItemClick when user press on ListView item.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, studentList[position].toString(),
Toast.LENGTH_LONG).show(); } });
2. Output as below. When i clicked the studentC item.
Remove line between row in ListView Item.
1. Add in below line in the activity_main.xml inside ListView
android:divider="@null"
THE END. HAPPY LEANING. :)
No comments:
Post a Comment