10 List view
Algorithm:
Step 1) Create a new Android Studio Project named as listview.
Step 2)Goto Project Structure and open activity_main.xml file
Step 3) Remove the default layout i.e Constraint layout and create ListView by using tag or drag and drop from the palette.
Step 3) Create String-array with the list of items within the resource tag in String.xml file (or) you can assign a list of item values to String [] in MainActivity class.
Step 4) Goto MainActivity class and create ListView class reference variable use Adapter classes which
add the content from the data source (such as string array, array, database etc) to ListView.
Step 5) implement the following method when the user clicks on any one of the list items which displays the Toast message.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
|
step 6) Run the application from the menu bar select Run and Click on Run App option.
Program:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/list_view"
android:layout_width="match_parent" android:layout_height="match_parent">
</ListView>
|
</android.support.constraint.ConstraintLayou >
MainActivity.java
package com.example.listview;
import android.support.v7.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
{ ListView listView;
String[] districts; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=findViewById(R.id.list_view); districts=getResources().getStringArray(R.array.ap_districts); final ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,districts);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String value=adapter.getItem(position); Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
}
}
OUTPUT:
After clicking on options
Comments
Post a Comment