Android Program : Create an Android Application that Demonstrate ListView and Onclick of List Display the Toast.
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"
android:background="#000000"
tools:context=".MainActivity">
<ListView
android:id="@+id/listViewID"
android:layout_width="match_parent"
android:layout_height="495dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.toast.listviewe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
ListView fruitView;
String[] fruits = new String[]
{
"satish",
"rajesh",
"Rakesh",
"Suraj",
"Dinesh",
"Kamlesh"
};
List<String> fruitList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fruitView = (ListView) findViewById(R.id.listViewID);
fruitList = new ArrayList<String>(Arrays.asList(fruits));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_2, android.R.id.text1, fruitList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView ListItemShow = (TextView) view.findViewById(android.R.id.text1);
ListItemShow.setTextColor(Color.parseColor("#ffffff"));
return view;
}
};
fruitView.setAdapter(adapter);
fruitView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "clicked item is " +fruits[position], Toast.LENGTH_SHORT).show();
}
});
}
}
0 Comments