I'm looking to be able to open up a new view or activity when I click on an item in my ListView.
Currently I have a list of restaurants, and when i click on a particular restaurant I want it to open up another screen that will show its address, google map etc.
What I need help with is knowing how to set click events on the items in the list.
At the moment I dont have a database of the items, they're just Strings.
Can someone help me with getting me to this stage?
Thanks alot.
package com.example.androidrestaurant;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.ListActivity;
public class Dundrum extends ListActivity {
TextView selection;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, DUNDRUM));
getListView().setTextFilterEnabled(true);
}
static final String[] DUNDRUM = new String[] {
"Ananda",
"Brambles Cafe", "Brannigans", "Buona Sera",
"Cafe Mao", "Cafe Mimo",
"Dante", "Douglas & Kaldi Terrace Cafe",
"Eddie Rockets",
"Frango's World Cuisine",
"Nando's",
"Overends Restaurant # Airfield House",
"Pizza Hut",
"Roly Saul",
"Siam Thai","Smokey Joes","Sohag Tandoori",
"TGI Friday","The Rockfield Lounge", "Winters Bar" };
};
You need to do like this :
// Store your listview into local variable
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Bind onclick event handler
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Put in your code here, what you wanted trigger :)
}
});
If you are using the ListView in a ListActivity, override onListItemClick(). Otherwise, use setOnItemClickListener() with the ListView. In either case, you are given a position that is the index into your array.
See here for an sample project.
Related
I am trying to understand where to save the selected list view items from this code. With a dialog box you have an "ok/cancel" button option, is this possible with lists? Ideally I will be storing data from four different lists into a database on submit. In the below picture I would like to save the first three items into a database, or even an array just to start.
package com.example.lifebyfourlists;
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 MainActivity extends ListActivity{
String [] seven = {
"Dark Leafy Greens" ,
"Nuts",
"Carrots",
"Green Tea",
"Whole Grains",
"Fruits"};
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lstView.setTextFilterEnabled(true);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, seven));
}
public void onListItemClick(ListView parent, View v, int position, long id){
Toast.makeText(this, "You have selected " + seven[position], Toast.LENGTH_SHORT).show();
}
}
I am trying to understand where to save the selected list view items from this code. With a dialog box you have an "ok/cancel" button option, is this possible with lists?
You can use getCheckedItemIds() or you can write a custom Adapter to track the selected rows.
Suppose I have displayed a list view(say lv1) of 3 items. when clicked on any of them I get new list view(say lv2). when again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. lv2 and again when back button is pressed I want to show list view lv1. can anybody tell me how I can do this?
If you want to shown different listviews in different activities. Follow Shailendra Rajawat's guide. Every time you click on an item, start a new Activity. So by default, when you press back button, the previous activity will be shown.
If you want to achieve this function within one activity. Use a variable to indicate which listview should be currently shown. Something like:
private int listIndex=0; every time you click on an item:listIndex++; and call setContentView(lvX); to show new listView.
Override the onBackPress() method:
if(listIndex>0) *so at the first listView backbutton will be ignored */
listIndex--;
switch(listIndex) {
case 0:
setContentView(lv0); break;
/* some other cases*/
........}
Something like this.
EDIT: I tested my method. Actually, there are three ways to refresh the listView.
package viewTest.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
public class ViewTestActivity extends Activity {
private ArrayAdapter<String> adapter0;
private ArrayAdapter<String> adapter1;
private String[] array0;
private String[] array1;
private ListView lv0;
private ListView lv1;
private RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array0 = getResources().getStringArray(R.array.LV0);
array1 = getResources().getStringArray(R.array.LV1);
adapter0 = new ArrayAdapter<String>(this, R.layout.item, array0);
adapter1 = new ArrayAdapter<String>(this, R.layout.item, array1);
lv0 = new ListView(this);
lv1 = new ListView(this);
layout=(RelativeLayout)findViewById(R.id.layout);
lv0.setAdapter(adapter0);
lv1.setAdapter(adapter1);
lv0.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//Method1: change the adapter to refresh the listview
// lv0.setAdapter(adapter1);
//Method2: use the layout to remove and add views
// layout.removeAllViews();
// layout.addView(lv1);
//Method3: setContentView() directly;
setContentView(lv1);
}
});
// layout.addView(lv0);
setContentView(lv0);
}
}
what you have described here it is obvious in Android Activity life cycle because when you hit back button it finish the current Activity and show the top most Activity on Stack . So please explain what problem you are getting here .
You can put some boolean to true if the second list view is showing. When back button is pressed, look at the boolean and change the listView to the first one.
as a neat and clean approach every screen you want to show on back press , should be on activity stack , so for every such views start a new activity even if they have same UI components .
if this approach is not suitable save data of every visible entity on navigations they reset views as per need by overRiding onBackPress().
I'm using the ListActivity class in conjunction with the simple_list_item_checked-layout which implements simple list items with checkboxes. Everything is working fine - clicking added items calls onListItemClick() and I can check/uncheck respective checkboxes of entries via the 'View v' parameter.
However what I wasn't able to figure out yet is, how to (pre)select checkboxes without any userinteraction?
Minimal so far working code snippet showing my intend:
package org.test;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
public class TestActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}
}
Thanks a lot in advance!
daten
This works for me:
You have to set the choicemode of the underlying ListView to single or multiple.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_checked);
list_elems.add("foobar");
//TODO: check added entry labeled "foobar"
setListAdapter(list_elems);
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setItemChecked(0, true);
}
Use a SimpleListAdapter as the ListAdapter for your ListActivity. Use two columns (one for your string and the other for the checked value), and the system should take care of it by itself. Here is a good example
I want to make a dynamic list view which gets the user credentials when I login for the first time and displays it in a list the next time I start the app. I know how to send the username from one intent to another. i haven't focused on the SQLite part yet, will do that later. I'm facing problems in creating the dynamic list view.
Found one very useful thread - Dynamically add elements to a listView Android
he used a button on the screen and called the method onClick to populate the list. Can i do it without the button? I want it to automatically happen once i am able to login.
how can i use the statements in my code?
listItems.add(value);
adapter.notifyDataSetChanged();
here value is the username i am getting from some other intent.
please help. thanks!
For this Just use the example given below:
For Instance you are Adding Some Strings into your List
So Create a ListArray like this
ArrayList<String> listItems = new ArrayList<String>();
now whenever you want to add certain string into list just do this thing
EditText editText = (EditText) findViewById(R.id.edit);
listItems.add("my string"); OR
listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list
Use this Xml inside your linear layout in main.xml
<EditText android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now when you have added one item dynamically then call this
adapter.notifyDataSetChanged();
The above will update your list and display the upadted list.
For more info about this see the following links:
http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3
In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.
Thanks
sHaH
The best way to do this will be to use ArrayAdapter. When modifying the adapter it automatically refresh itself so you don't have to call notifyDataSetChanged.
You can try out this code to add elements dynamically to list view.
You can do it with out button click also.
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//step2 : create all the variables.
EditText et;
Button b;
ListView lv;
ArrayList<string> al;
ArrayAdapter<string> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//step3 : intitalize all the variables.
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
lv = (ListView) findViewById(R.id.listView1);
al = new ArrayList<string>();//initialize array list
aa = new ArrayAdapter<string>(this,
android.R.layout.simple_list_item_1,
al);//step4 : establish communication bw arraylist and adapter
//step5 : establish communication bw adapter and dest (listview)
lv.setAdapter(aa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent,
View v, int arg2,
long arg3) {
String item = al.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
//step6 : button click logic
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//step i: take text from et and add to arraylist
String item = et.getText().toString();
al.add(0, item);
//step ii: notify to adapter
aa.notifyDataSetChanged();
//step iii: clr edit text
et.setText("");
}
});
}
}
For complete code check this list view example
I am wondering how could i divide my ListView in parts and display only one part of it when user starts my app and display others when user press a Button called "Load More Items".
I have a big list of more than 500 items and thinking to divide it into parts so it could load fast.
I want functionality similar to an any email app which gives an option at the bottom to load more emails.
If anyone has any sample code for my problem then please share else a little guidance would also be appreciated.
well implementing a button is easy enough:
in your onCreate, load your adapter with the 1st 50 items, then implement a button with an onClickListener that adds the next 50 etc.
HOWEVER
I think what you really want to do is lazy load your listview so as they scroll, it will load more items - that why you don't need to clutter the UI with an extra button.
for this your listactivity should implement OnScrollListener
here is an example of that: Android Endless List
From your question, it seems that you want to load few items initially and then load more items in future whenever user click on the "Load More items" button.
For that there can be two cases possible:
First case: webservice can send response in parts, like first time it sends 20 items, and next time 20 items whenever user clicks on "Load more items" button.
Second case: If you get 500 items in response, then to implement "Load more items" kind of functionality, you have to create database table to store all the items. Once you are done with database value storing, fetch 20 items initially, next time load 20 items and so on.
Initially load part of data in your list view.
You have to use concept of Handler. onclick event you have to send message to handler inside handler you have to write the logic to load your full data and call notifydataSetChanged method
have a look on the sample code below. Initially user is able to see some part of list. If user cvlicks on any list item then list user is able to see the whole list view. It is similar to as that you are expecting.
Sample Code
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MyListView extends ListActivity {
ArrayList<String> pens = new ArrayList<String>();
ArrayAdapter arrayAdapter = null;
private static final byte UPDATE_LIST = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pens.add("MONT Blanc");
pens.add("Gucci");
pens.add("Parker");
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, pens);
setListAdapter(arrayAdapter);
getListView().setTextFilterEnabled(true);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("..Item is clicked..");
Message msg = new Message();
msg.what = UPDATE_LIST;
updateListHandler.sendMessage(msg);
}
});
// System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234"));
// System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4"));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
System.out.println("...11configuration is changed...");
}
void addMoreDataToList() {
pens.add("item1");
pens.add("item2");
pens.add("item3");
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, id + "You have chosen the pen: " + " " + pen,
Toast.LENGTH_LONG).show();
}
private Handler updateListHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_LIST:
addMoreDataToList();
arrayAdapter.notifyDataSetChanged();
break;
}
;
};
};
}
Thanks
Deepak