Android Programming

Hands On No. 14 : Working with Listview

Resources for Creating Listview

Source Code of MainAcivity.java
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] subjectName = {"C","C++","Java","Python","Android","Kotlin","Dart"};

ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.list_view, subjectName);

ListView listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

String value = "You have selected " + adapter.getItem(position) +" Language";

Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
});

}
}
Source Code of 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:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Source Code of list_view.xml
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="12dp"
android:textSize="18dp"
android:textStyle="bold" >
</TextView>