I've been browsing all possible sites for ages and haven't found my needs yet. I rly need to find a code-example of a basic listview in android that lets me click on the items in the list and takes me to an imageview displaying an image (different for every item in the list). Please post a working samplecode for this as it's driving me mad that I can't figure it out :(
I'm not going to go into detail about creating the ListView or setting an adapter or any of that stuff, there's plenty of other examples on the Web to do that and your question isn't asking how to set a ListView adapter ;)
Create an activity that extends ListActivity
Create a layout for your new ListActivity and put a ListView in it
(#+id/list) for my example
What's in your list? idk, but lets say it's an ArrayList of strings
now override onListItemClick in your ListActivity
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
if (l.getItemAtPosition(position).equals("LIST1"))
{
// Do something with it
}
}
Alternatively, you don't need a ListActivity, you can set an onItemClickListener
e.g.
myListView.setOnItemClickListener(new onItemClickListener()
{
#Override protected void onListItemClick(ListView l, View v, int position, long id) {
// Do stuff
}
}
check that link
all you need to do is change the OnItemClickListener() method
Ok here's the code, first we got the list menu.
package item.list.lol;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity {
String classes[] = {"startingPoint", "lol"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String pointer = classes[position];
try{
Class ourClass = Class.forName("item.list.lol." + pointer);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
And then the class that handles the imageView
package item.list.lol;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class startingPoint extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(R.drawable.ic_launcher);
}}
And the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.67"
android:src="#drawable/ic_launcher" />
</LinearLayout>
As you see it can now only display an image if I press the first item in the list, I need a way to make it display different images if I click different items, any ideas?
Related
I have an expandablelistview as shown below. I've made it so that a toast message will pop up when each child is clicked. I need each of the children to start their own activity/fragment, which required individual onClick() methods. Does anybody know how this can be achieved? Thanks. NOTE: I am using SimonVT's slidingmenu library and I'm pretty new to android programming.
MainActivity.java:
package press.linx.expandablelistdemo;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xml.sax.SAXException;
import net.simonvt.menudrawer.MenuDrawer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListView exv;
MenuDrawer mDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDrawer = MenuDrawer.attach(this);
mDrawer.setContentView(R.layout.activity_main);
mDrawer.setMenuView(R.layout.leftmenu);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String itemclicked = MyAdapter.childList[groupPosition][childPosition];
Toast.makeText(getApplicationContext(), "you clicked " + itemclicked, Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void setListAdapter(SimpleAdapter adapter) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MyAdapter.java
package press.linx.expandablelistdemo;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
Typeface typeface;
String []parentList = {"Tech", "Best Of", "Art & Design", "Other"};
static String [][] childList = {
{
"All Tech", "Reviews", "Gaming", "Gadgets"
},
{
"Android"
},
{
"Architecture"
},
{
"Infographics"
}
};
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
//typeface = Typeface.createFromAsset(context.getAssets(), "font/robotochild.ttf");
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(30, 10, 0, 10);
tv.setTextSize(15);
//tv.setTypeface(typeface);
tv.setTextColor(Color.WHITE);
return tv;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView tv = new TextView(context);
typeface = Typeface.createFromAsset(context.getAssets(), "font/roboto.ttf");
tv.setText(parentList[groupPosition]);
tv.setPadding(50, 10, 0, 10);
tv.setTextSize(20);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface);
return tv;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
menulistview.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/geowall">
<ExpandableListView
android:id="#+id/expandableListView1"
android:groupIndicator="#null"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="3dp" >
</ExpandableListView>
!
If you want differing functionalities per button, consider storing them as the buttons' tag property (in the XML layout). The View v parameter in your onChildClick listener is the View of the child being clicked; it can then be used to retrieve the tag, like so:
v.getTag();
You could either have a switch-case block to call the correct activity based on the tag, or store the exact name of the activity in the tag and pass that in via reflection to retrieve the class for the activity. Alternatively, you could store a HashMap mapping the tag-names to Activity classes/variables.
This might be you are looking for.
Let’s get start by creating a project in Eclipse IDE.
Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as AndroidListViewActivity.
Once the project is created open your main activity java file (in this case AndroidListViewActivity.java) and extend the class from ListActivity.
public class AndroidListViewActivity extends ListActivity {
3. Now we need a string resources file to store all list item labels. So create an XML file under values folder and name it as list_data.xml and paste the following code.
( Right Click on res/values ⇒ New ⇒ Android XML File)
list_data.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="adobe_products">
<item>Adobe After Effects</item>
<item>Adobe Bridge</item>
<item>Adobe Dreamweaver</item>
<item>Adobe Edge</item>
<item>Adobe Fireworks</item>
<item>Adobe Flash</item>
<item>Adobe Photoshop</item>
<item>Adobe Premiere</item>
<item>Adobe Reader</item>
<item>Adobe Illustrator</item>
</string-array>
</resources>
In ListView each list item will be an xml layout, so we can customize each list item. Create an XML file under res/layout folder and name it as list_item.xml and type the following code. This xml layout will be single list item row.
( Right Click on res/layout ⇒ New ⇒ Android XML File)
Now open your main activity java file (AndroidListViewActivity.java) and type the following code. In the following code i am importing all xml resources data and storing them in an Array. On the next step i am binding array to ListAdapter.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
}
}
Now run your project you can see listview with list of array items. But on clicking single list item you can see no action. So we need to start new activity on selecting single list item.
Launching new Activity on selecting single list item
In my previous article i had explained how to switch between screens. Here i am going to show single list item details in new screen.
Now create new activity class under src folder. Right Click on src/package folder ⇒ New ⇒ Class and name it as SingleListItem. (SingleListItem.java)
Open your AndroidListViewActivity.java and modify the code to following. In the following code i am getting the selected list item string(product name) and sending it to new Activity.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
}
}
Now in new activity we need to display the received from listview activity.
Create a new xml file under res/layout and name it as single_list_item_view.xml and type the following code. This XML file will be layout for SingleListItem.java
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
Now open your second activity file i.e SingleListItem.java and paste the following code.
SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
The final step is to add an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.androidlistview"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidListViewActivity"
android:label="Android List View">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.
I am trying to make a list view search for Android. I have found many tutorials that do just that where
a search-bar is placed at the top and if you type in the box the results get filtered.
In my app I want to click on given items after filtering has been completed, I have implemented setOnItemClickListener. The issue is that after filtering the position of each class that I want to open changes and the incorrect pages open. I was unable to find a solution....
Here is the jave code:
package com.equations.search;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class EquationsSearch extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.equations_search);
// Listview Data
final String products[] = { "Dell Inspiron", "HTC One X",
"HTC Wildfire S", "HTC Sense", "HTC Sensation XE" };
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this,
R.layout.equations_search_list, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
EquationsSearch.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChange(Editable arg0) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// if(position == 1)
String openClass = products[position];
if (openClass.equals("HTC Wildfire S")) {
// code specific to first list item
Intent myIntent = new Intent(view.getContext(), A6262.class);
startActivityForResult(myIntent, 0);
}
}
});
}
}
and here is the xml equations_search.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>
<!-- List View -->
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and equations_search_list.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"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/product_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
Thank you in advance.
Rather than products[position], use adapter.getItem(position). When the ListView is not in filter mode, those two things will be the same. But, in filter mode, getItem() will take the filtering into account.
The ListAdapter will change the relative position of the items it currently shows due to the filtering. You should always use getItem(position) to retrieve the correct item.
Hi I want to built a android a application with a ListView and if I select a value in this ListView I want to start a other activity with this value. The Problem is I don't know how I can click on a value in my ListView and the other activity get the informations. Here is my Code:
My First Activity:
package de.android.shilfe;
import de.android.shilfe.DatenbankManager;
import de.android.shilfe.R;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class MainActivity extends ListActivity {
private SQLiteDatabase mDatenbank;
private DatenbankManager mHelper;
private static final String KLASSEN_SELECT_ROW =
"SELECT _id, name FROM Stundenplan";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper.STUNDENPLAN_CREATE = "CREATE TABLE Stundenplan(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
"name TEXT NOT NULL)";
mHelper = new DatenbankManager(this);
//what I must do here ??? :(
}
#Override
protected void onPause() {
super.onPause();
mDatenbank.close();
Toast.makeText(this,
getResources().getString(R.string.db_close),
Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
mDatenbank = mHelper.getReadableDatabase(); //Datenbank öffnen
Toast.makeText(this,
getResources().getString(R.string.db_open),
Toast.LENGTH_SHORT).show();
ladeDaten();
}
private void ladeDaten() {
Cursor KlassenCursor = mDatenbank.rawQuery(KLASSEN_SELECT_ROW, null); // Gibt ein Index zurück
startManagingCursor(KlassenCursor); //Durchläuft diesen
android.widget.SimpleCursorAdapter KlassenAdapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
KlassenCursor,
new String[] {"name"},
new int[] {
android.R.id.text1
});
setListAdapter(KlassenAdapter);
}
public void onButtonClick(View view){
EditText et =(EditText) findViewById(R.id.editText1);
ContentValues werte = new ContentValues();
werte.put("name",et.getText().toString());
mDatenbank.insert("stundenplan", null, werte);
ladeDaten();
et.setText("");
}
}
My First Activity Layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="5">
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/create_defaulttext">
<requestFocus />
</EditText>
<Button
android:id="#+id/sf_daten_datenbanken_einfuegen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/sf_daten_datenbanken_einfuegen"
android:onClick="onButtonClick" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>
<TextView
android:id="#+id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tx_daten_datenbank_leer"/>
</LinearLayout>
</LinearLayout>
I try it in a other Application with this code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List valueList = new ArrayList<String>();
for(int i=0;i<10;i++)
{
valueList.add("value" + i);
}
ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,valueList);
final ListView lv = (ListView)findViewById(R.id.listview1);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
Intent intent = new Intent();
intent.setClassName(getPackageName(), getPackageName() + ".Show_Activity");
intent.putExtra("selected",lv.getAdapter().getItem(arg2).toString());
startActivity(intent);
}
});
}
but in the other Application I fill the ListView by a EditText Control
I need help :(
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent intent = new Intent(context, Show_Activity.class);
intent.putExtra("selected", (String) lv.getItemAtPosition(position));
startActivity(intent);
}
});
You already did pass the value to another activity with putExtra
Hey You question is not complete but I am giving this answer as per what I understand. In the onListItemClick() method last parameter of long datatype is id of a row selected. in your case, it will _id of table. If you have 10 rows in your table with id 10 to 20 and displayed the same in listview. Now if you click on 5 item then its id will be 15 which was stored in database. Pass this value to next intent and fetch the details of that row and display in the next activity.
When you use a ListActivity so you can use onListItemClick method.This method will be called when an item in the list is selected.
You can to create a custom list adapter and handle the onClick event in the getView method of the adapter. The item will be available in this method.
public class AccountListAdapter extends ArrayAdapter<Account> {
#Override
public View getView(int position, View convertView, ViewGroup parent){
final Account item = this.getItem(position);
// item = the particular list item you clicked
// layoutItem = layout view passed into the adapter
layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callActivity(item);
}
});
}
}
While handling the event, create an intent with extras and pass the value(s) you desire via the extras. You can use a simplelistadapter, but this way gives you considerably more control and power!
Hi I am trying to make an app that shows a list of items using listView and when the user select one of the items from the list. the app will call the specific class that is link to the item selected however i encountered an error at the second #override, saying that the override must override a super class. Here are my codes for class and xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/botanicgate" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
package com.fyp.gulliver;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends ListActivity{
/** Called when the activity is first created. */
String places[] = {"BotanicGarden", "Sentosa"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotspot);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter
(HotSpot.this, android.R.layout.simple_list_item_1,
places));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Class ourClass;
String item = ((TextView)view).getText().toString();
try {
ourClass = Class.forName
("com.fyp.gulliver." + item);
Intent ourIntent = new Intent(HotSpot.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
As i am still new to android, thus i do not know what mistakes i have made, I will be grateful if another one can help me to solve my error thank you :D
Try changing this:
listView.setOnItemClickListener(new OnItemClickListener();
to
listView.setOnItemClickListener(new AdapterView.OnItemClickListener();
and remove the 2nd #Override
I am trying to set up an OnItemClickListener for a ListView that was created inside of the main activity (extending Activity). The following code is not firing. Why isn't the onItemClick running?
Main.java
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class Main extends Activity {
/** Called when the activity is first created. */
List<Title> titleList;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set list view
setContentView(R.layout.listview);
setTitle("TITLE");
// Create Parser for raw/countries.xml
TitleParser titleParser = new TitleParser();
InputStream inputStream = getResources().openRawResource(R.raw.titles);
// Parse the input stream
titleParser.parse(inputStream);
// Get Titles
titleList = titleParser.getList();
// Create a customized ArrayAdapter
TitleArrayAdapter adapter = new TitleArrayAdapter(
getApplicationContext(), R.layout.title_listitem, titleList);
// Get reference to ListView holder
lv = (ListView) this.findViewById(R.id.titleLV);
// Set the ListView adapter
lv.setAdapter(adapter);
// on list item click
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Title title = (Title) lv.getItemAtPosition(position);
try{
Class<?> challengeClass = Class.forName("com.glvangorp.app.TITLECHALLENGE");
Intent challengeIntent = new Intent(Main.this, challengeClass);
challengeIntent.putExtra("challenge", title.challenge);
challengeIntent.putExtra("title", title.resourceId);
startActivity(challengeIntent);
} catch(ClassNotFoundException e){
Log.d("TAG", e.getMessage());
e.printStackTrace();
}
}
};
lv.setOnItemClickListener(listener);
}
}
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/titleLV"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
one reason one not calling is the list item has been set to clickable false. or on the list item you have set some click or touch listener with return true ( make it to return false if you have written).
Maybe it is getting called but you are just getting an ClassNotFoundException thus, you don't know if it doing anything in the OnItemClick ... Why don't you put a Log.d("TAG", e.getMessage); inside the
catch clause.