Android ListView - how to react to item clicks? - android

Let's say that I have a ListView with some items. I want to make it so when the user clicks on an item, the app pops up a Toast containing the name of the item. For example, when the user clicks "Apple", they are presented with the toast: "You ate Apple." How can I do so?

Standard way it to use .setOnItemClickListener().

you can set Item Click Listener on List View i.e.
listvw=(ListView)findViewById(R.id.listviewid);
listvw.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(ActivityName.this, "Text message", Toast.LENGTH_SHORT).show();
}
});

use like that
ActivityListView .java
package com.sunil;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ActivityListView extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create an array of Strings, that will be put to our ListActivity
String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse",
"Suse", "Ubuntu", "Solaris", "Android", "iPhone" };
/* Create an ArrayAdapter, that will actually make the Strings above
appear in the ListView */
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, namesArray));
}
#Override
protected void onListItemClick(ListView l, View v,
int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword,
Toast.LENGTH_SHORT).show();
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>

Try this code
listview=(ListView)findViewById(R.id.listid);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {
// to set your list item or name
//here list is your list that you set in your adapter
list.get(pos);
}
});

Related

Adding onClickListener to specific items in ListView

please I'm trying to add understand how to add onItemClickListener to the followng code such that when "Smartphone Plans" is clicked, its activity starts and so on. I've seen other questions on StackOverflow relating to this question but do not understand how to go about them.
I've already added an onItemClickListener but do not understand how to set it to specific list items.
here is the code
package devchuks.com.rechargeit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EtisalatData extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etisalat_data);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"Smartphone Plans",
"Internet Bundles",
"Weekend Plans",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
You can define your listView.setOnItemClickListener like this to go to different activity for clicking different element.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = listView.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
if(position==0) {
// Do your code for clicking "Smartphone Plans" example
// startActivity(new Intent(getApplicationContext(),SmartphonePlans.class));
}
else if(position==1) {
// Do your code for clicking "Internet Bundles". example
// startActivity(new Intent(getApplicationContext(),InternetBundles.class));
}
else if(position==2) {
// Do your code for clicking "Weekend Plans". example
//startActivity(new Intent(getApplicationContext(),WeekendPlans.class));*/
}
});
onItemClick will be called whenever any of the list items are clicked. The position will be the position of the view in the Adapter.
Please refer -
How to handle the click event in Listview in android?
Thanks
Sriram
try this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = values[position];
if(text.equals("Smartphone Plans")){ //your specific list item text
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
i.putExtra("TEXT", text);
startActivity(i);
}
}
}
If this helps and is your concern
`
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = values[position];
switch(data){
case "Smartphone Plans":
// do somwthing
break;
// similarly for other two values.
}
}
});`
Below method give you a position of a clicked row. Take advantage of that and value from your array.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Move your values array to member array or make it final to use
// in Anonymous class
final String selectedValue = values[position];
Intent intent = null
// Now add case and start activity
if("Smartphone Plans".equals(selectedValue)) {
intent = new Intent(EtisalatData.this, SmartPhonePlan.class);
}
else if("other Plans".equals(selectedValue)){
// other action
}
//... more cases and at the end start your activity if its not null
startActivity(intent);
}

Extracting 2 strings from 2 listviews in adroidstudio

I have 2 listviews in 1 activity (1 on the left 1 on the right of screen). I want 2 strings extracted from both list views and use them else where in the code (either in the same activity but different class or different activity). I have tried assigning clicked items to a public variable and then posting them on a text view bit I see nothing. Please help or suggest another better way. Here is a sample of my code:
public class Tabs extends Activity {
String CF =""; //Convert To
String CT =""; //Convert From
populateListView(); //function that populates my listview (not shown here)
ListView listMassFrom = (ListView) findViewById(R.id.ListViewMassFrom);
ListView listMassTo = (ListView) findViewById(R.id.ListViewMassTo);
listMassFrom.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
String convFrom = ((TextView) viewClicked).getText().toString();
CF = convFrom;
}
});
listMassTo.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
String convTo = ((TextView) viewClicked).getText().toString();
CT = convTo;
}
});
//Test to see if the two string were extracted from the onItemClick method:
TextView t1 = (TextView) findViewById(R.id.test1);
t1.setText(CT);
TextView t2 = (TextView) findViewById(R.id.test2);
t2.setText(CF);
}
}
You should access items via adapters using the parameter position.
Supposing your adapter contains Strings (Otherwise adapt it to your data model):
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
CF = <listMassFrom_adapter>.getItem(position);
}
EDIT:
Example tested and working. You can see a toast when items are selected.
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.testbutton.R;
public class Tabs extends Activity {
final static String[] MassUnits = { "kg", "g", "mg", "lb", "lbm", "slug" };
String CF = ""; // Convert To
String CT = ""; // Convert From
ListView listMassFrom, listMassTo;
ListAdapter adapterFrom, adapterTo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
// Find views
listMassFrom = (ListView) findViewById(R.id.lvFrom);
listMassTo = (ListView) findViewById(R.id.lvTo);
// Create list of items
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MassUnits);
listMassFrom.setAdapter(adapterFrom);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MassUnits);
listMassTo.setAdapter(adapterTo);
listMassFrom
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View viewClicked, int position, long id) {
String convFrom = (String) adapterFrom
.getItem(position);
Toast.makeText(getApplicationContext(),
"From: " + convFrom, Toast.LENGTH_SHORT).show();
}
});
listMassTo
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View viewClicked, int position, long id) {
String convTo = (String) adapterTo.getItem(position);
Toast.makeText(getApplicationContext(),
"To: " + convTo, Toast.LENGTH_SHORT).show();
}
});
}
}
Layout tabs.xml:
<?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" >
<ListView
android:id="#+id/lvFrom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ListView
android:id="#+id/lvTo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I think it is better to use spinners, but you can adapt the code if that's the case.

How to get value from spinner in android ?

How to get values from drop down menu and use them in body of new message to be send.
Following is my code,
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
String phoneNo = editPhoneNum.getText().toString();
String sms = editSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,Toast.LENGTH_LONG).show();
}
}
try this
ArrayList<String> list = new ArrayList<String>(); //make this as field atribute
list.add("A");
list.add("B");
list.add("C");
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
list.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Declare your String label and String phoneNo variables globally and then pass it in your message body.
Append your spinner item in your sms string.
Supposing your class code
public class MainActivity extends Activity {
private String phoneNo,sms,label;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.............................
phoneNo = editPhoneNum.getText().toString();
sms = editSMS.getText().toString() + label;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
String label = parent.getItemAtPosition(position).getvalue();
getvalue().. according to location ur going getting only position. you have to get value yes use what value u want to get insted of getvalue() function name
Hi please have a look how we can do this i am sending example to you.
please look here
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
the full example is shown here as follows.
AndroidSpinnerExampleActivity.java
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Text Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"
/>
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"
/>
</LinearLayout>

ListView within ListView in android application

I am doing a project that currently requires a list and when a particular item from the list is clicked another list activity appears. Is there any solution as to how to move from one listview activity to another. I am currently using http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/ as a reference for my ListView.
One solution would be:
Create the second ListView activity and implement the first ListActivity with a OnItemClickListener that opens the second ListViewActivity by using an regular Intent.
listView = (ListView) findViewById(R.id.mylistview);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent intent = new Intent(FirstListActivity.this, SecondListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("pos", position);
intent.putExtras(bundle);
startActivity(intent);
}
});
UPDATE:
I have wrote an simple example list application. You may use it for insperation. The code that could open the Second list activity is included, but commented out. If you get this example to run, you are getting closer. Then you can try comment out the Intent code.
package com.adpog.listviewexample;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
ListView mainListView = (ListView) findViewById( R.id.my_list );
// Set the Adapter as the ListView's adapter.
mainListView.setAdapter( new BaseAdapter(){
// Create and populate a List of planet names.
String[] planets = new String[] {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
#Override
public int getCount() {
return planets.length;
}
#Override
public Object getItem(int pos) {
return planets[pos-1];
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(int pos, View view, ViewGroup viewgroup) {
if(view == null){
/**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text not set" />
</LinearLayout>
*/
view = View.inflate(getApplicationContext(), R.layout.row, null);
}
return view;
}
});
mainListView.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int arg2, long arg3) {
Log.d("ListView", "Pos: " + arg2 + ", long : "+arg3);
Toast.makeText(getApplicationContext(), "Test " + arg2, Toast.LENGTH_SHORT).show();
/* Alternative way; opens a new Activity
Intent intent = new Intent(this, SecondListViewActivity.class);
intent.putExtra("position", pos);
startActivity(intent);
*/
}
#Override
public void onNothingSelected(AdapterView< ? > arg0) {
}
});
/**
* Implement an action for each item click.
*/
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView< ? > arg0, View arg1, int arg2, long arg3) {
Log.d("ListView", "OnClickPos: " + arg2 + ", long : "+arg3);
Toast.makeText(getApplicationContext(), "Test " + arg2, Toast.LENGTH_SHORT).show();
}
});
}
}
api provides ExpandableListView . your requirement looks very close to it

Android - Dynamically Adding values to Spinners

I am new to Android Development so the query may seem novice.
I was trying to make an app where there are a couple of spinners and after the user selects one spinner the other spinner gets filled up with the data based on the selection in spinner1.
ie. First user selects Country. Based on country the spinner 2 gets filled up with states and based on the state the spinner 3 gets filled up with cities.
I have created all the countries as a string arrays in strings.xml like -
<string-array name="Country">
<item >USA</item> etc...
Similarly states have been created in the string.xml as - (Each Country is a separate entry with a naming convention as (country name)_(States)
<string-array name="USA_state">
<item >New York</item> etc...
Now I want the second spinner to populate based in country selection. Hence the formula used by me is to the get the second spinner is -
String getstate = country[index]+"_"+"state";
state=getResources()
.getStringArray(getResources().
getIdentifier(getstate,null,getPackageName()));
When I run this app the Manactivity just shows a blank screen and I donot get any Debug info and get an error "the jar file android.jar has no source attached".
Please help. The complete mainActivity is given below -
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.view.View;
public class MainActivity extends Activity {
String[] country;
String[] state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country = getResources().getStringArray(R.array.country);
Spinner country_spinner =(Spinner) findViewById(R.id.country);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+"country", Toast.LENGTH_SHORT).show();
Fill (index);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
protected void Fill(int index) {
// TODO Auto-generated method stub
//Field resField=R.array.getField(country[index]);
//int getstate = resField.getInt(null);
String getstate = country[index]+"_"+"state";
state=getResources().getStringArray(getResources().getIdentifier(getstate,null,getPackageName()));
Spinner state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state);
state_spinner.setAdapter(adapter);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index2 = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),"You Have Selected "+state[index2] + " statet",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
I was able to solve the problem. The final code is given below. This is a nested approach so if there are 3 spinners (like city after state) do we again nest the code for that spinner? Is there any simpler method?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+" County", Toast.LENGTH_SHORT).show();
final CharSequence[] state_array = state.getTextArray(index);
final Spinner state_spinner =(Spinner) findViewById(R.id.state);
ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(MainActivity.this, android.R.layout.simple_spinner_item, state_array);
state_spinner.setAdapter(adapter1);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
final int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+state_array[index]+" State", Toast.LENGTH_SHORT).show();
});
}
public void onNothingSelected(AdapterView<?> arg0) {
state_spinner.setAdapter(null);
}
});

Categories

Resources