AndroidManifest.xml:
MainActivity.java:
activity_listview.xml: under res/layout
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.blogspot.codingatharva.manualprograms"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
MainActivity.java:
package com.blogspot.codingatharva.manualprograms; 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.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { ListView lv; TextView tv; String langList[] = {"Android", "Java", "PHP", "Hadoop", "SAP", "Python", "AJAX", "C++", "Ruby", "Rails"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = findViewById(R.id.lv); ArrayAdapter<String> ad = new ArrayAdapter<String>(this, R.layout.activity_listview, R.id.tv, langList); lv.setAdapter(ad); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String selected = ((TextView) view.findViewById(R.id.tv)).getText().toString(); Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT).show(); } }); } }
activity_main.xml:
<?xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout 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:layout_margin="16dp" tools:context=".MainActivity"> <ListView android:id="@+id/lv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:dividerHeight="01dp" /> </RelativeLayout>
activity_listview.xml: under res/layout
<?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"> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout>