onListItemClick on Activity extends ListActivity - android

I try a listview but when I click on an element I have not my toast
public class MarkersListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titles = new String[] {"Titre 1", "Titre 2", "Titre 3", "Titre 4"};
String[] des = new String[] {"des 1", "des 2", "des 3", "des 4"};
setListAdapter( new MarkerListArrayAdapter(this, titles, des));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
}
}
MarkerListArrayAdapter
public class MarkerListArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] titleText;
private final String[] descriptionText;
public MarkerListArrayAdapter(Context context, String[] titles, String[] description) {
super(context, R.layout.marker_list_layout, titles);
this.context = context;
this.titleText = titles;
this.descriptionText = description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.marker_list_layout, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.title);
TextView description = (TextView) rowView.findViewById(R.id.description);
ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
title.setText(titleText[position]);
description.setText(descriptionText[position]);
imageView.setBackgroundColor(Color.argb(255,255,0,0));
return rowView;
}
}
The 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"
android:padding="5dp" >
<ImageView
android:id="#+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:src="#drawable/transparent" >
</ImageView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="30sp" >
</TextView>
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
Thanks

You should use the:
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
method instead.
Let you Activity: implements AdapterView.OnItemClickListener
and then in the onCreate add this command:
list.setOnItemClickListener(this);

You have not called super of onListItemClick()...
Do as follows:
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
}

You have to set setContentView(R.layout.activity_main) method in MarkersListActivity class and your listview ID should be "#android:id/list"
Add this layout activity_main
<?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"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#android:id/list" //Important this one.
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
</LinearLayout>
Have a look at the official documentation for listactivity
https://developer.android.com/reference/android/app/ListActivity.html

Related

Android Custom Spinner unable to select an option and show it

I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.
The picture shows that the spinner is in blank when the activity load
When I clicked the arrow it shows the items
but when I choose one, nothing happends.
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".Activities.Inspeccion.DatosGeneralesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
>
<TextView
android:id="#+id/tvSubestacionTitulo"
android:layout_below="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strSubestacion"
android:textSize="18sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
/>
<TextView
android:id="#+id/tvSubestacionDato"
android:layout_below="#+id/tvSubestacionTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Prueba"
/>
<Spinner
android:id="#+id/spinnerSubEstacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvSubestacionDato"
>
</Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is the Layout of the activity.
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tvNumeroOpcion"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="1"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDescriptionOption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Guatemala"
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
That is the custom layout for the spinner
Public class ComboAdapter extends BaseAdapter{
private List<Combo> combos;
private Activity activity;
private LayoutInflater inflater;
public ComboAdapter(List<Combo> combos, Activity activity) {
this.combos = combos;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return combos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, null);
TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);
tvId.setText(combos.get(position).getId());
tvDescripcion.setText(combos.get(position).getDescripcion());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getView(position, convertView,parent);
}
}
That is my Adapter
And below is my activity.
public class DatosGeneralesActivity extends AppCompatActivity {
private TextView tvSubestacionDato;
private List<Combo> listaCombo;
private Spinner spinnerSubestacion;
private ArrayAdapter<Combo> adapterSubestacion;
String seleccion;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_generales);
//Inicializando textos
tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);
//Inicializanco listas
listaCombo = new ArrayList<>();
//Inivializando spinners
spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);
AppService service = API.getCombos().create(AppService.class);
Call<List<Combo>> subestacionCall = service.getSubestacion();
subestacionCall.enqueue(new Callback<List<Combo>>() {
#Override
public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
listaCombo.clear();
listaCombo.addAll(response.body());
}
#Override
public void onFailure(Call<List<Combo>> call, Throwable t) {
}
});
//final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
spinnerSubestacion.setAdapter(adapter);
spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Try this changes:
Call adapter like:
ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
now in adapter class:
public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){
super(context,resouceId,textviewId, list);
this.combos = list;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also inside your getView() method inflate layout like:
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, parent , false);

Listview inside DialogueFragment unclickable

My app has listview inside dialogueFragment , when user chose item it should Toast , in my case items unclickable .
DialogueFragment
public class HistoryDialogue extends DialogFragment {
ListView list ;
Cursor c ;
HistoryAdapter adapter ;
Context context ;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.history,null);
list = (ListView)view.findViewById(R.id.listView);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
ContentResolver resolver = getActivity().getContentResolver();
c=resolver.query(Contract.SaveRunning.CONTENT_URI,null,null,null,null);
adapter= new HistoryAdapter(getActivity(),c,0);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"keep going ",Toast.LENGTH_LONG).show();
}
});
builder.setView(list);
return builder.create();
}
}
CursorAdapter
public class HistoryAdapter extends CursorAdapter {
public HistoryAdapter(Context context, Cursor c, int flags) {
super(context,c, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.historylist, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView text = (TextView) view.findViewById(R.id.text);
String body = cursor.getString(cursor.getColumnIndex("name"));
text.setText(body);
}
}
history.xml
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
historylist.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text"
android:layout_margin="5dp"
android:layout_weight="1"/>
<Button
android:layout_width="30dp"
android:layout_height="35dp"
android:background="#drawable/delete"
android:id="#+id/btn"
android:layout_margin="10dp"
android:layout_weight="0"
/>
Add android:focusable="false" in your ListView (in history.xml ) and Item main layout (in historylist.xml).
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
and
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:focusable="false"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
...
Add this line to your CursorAdapter's bindView:
((ViewGroup)row).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
if it isn't enough, add clickable="false" to your historylist.xml's Button

Can't get text from a textview in a listview

I have a custom cursor adapter CAdapter having the following lines of code:
public class CAdapter extends CursorAdapter {
public CAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView titleTV = (TextView) view.findViewById(R.id.listTitle);
titleTV.setText("#"+cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1)))+" "+
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row_item_layout, parent, false);
return retView;
}
}
row_item_layout.xml file is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/listTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="2dp"
android:layout_toRightOf="#+id/heartIV"
android:focusable="false"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="26sp"
android:paddingBottom="3dp"/>
<ImageView
android:id="#+id/heartIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/listTitle"
android:src="#drawable/heart"
android:paddingRight="5dp"
android:paddingLeft="2dp"/>
</RelativeLayout>
The activity FavListActivity displays the list. Its layout file is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xkcdreader.FavListActivity"
tools:ignore="MergeRootFrame" >
<ListView
android:id="#+id/favL"
android:layout_width="match_parent"
android:layout_height="452dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/headingTV" >
</ListView>
<TextView
android:id="#+id/headingTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:text="Favourites"
android:textSize="25dp" />
</RelativeLayout>
Following is a section of code from FavListActivity
listView = (ListView) findViewById(R.id.favL);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("App", "clicked on item: " + position);
TextView listTV=(TextView) view.findViewById(R.id.titleTV);
Log.d("App",listTV.getText().toString());
}
});
On running this I get NullPointerException at the line Log.d("App",listTV.getText().toString()); The list does not having any null textview. I can't figure out the problem. Please help
you should use getItemAtPosition:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor mycursor = (Cursor)parent.getItemAtPosition(position);
}
});
and use myCursor to access your data.
Try this..
Your TextView id is listTitle but you have mentioned as titleTV change that and try it.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("App", "clicked on item: " + position);
TextView listTV=(TextView) view.findViewById(R.id.listTitle);
Log.d("App",listTV.getText().toString());
}
});
There is no TextView in row_item_layou.xml with id titleTV. So when you initialize you end up getting NUllPointerException.
Change this
TextView listTV=(TextView) view.findViewById(R.id.titleTV);
to
TextView listTV=(TextView) view.findViewById(R.id.listTitle);
since you have
<TextView
android:id="#+id/listTitle" // id is listTitle
Although your NPE can be solved as above you are better off using blackbet's answer
Cursor mycursor = (Cursor)parent.getItemAtPosition(position);
Then get the String using the mycursor.

Get Item from a ListView

My app is displaying 3 String with 3 Text-view in a list-view.
My Problem is that I create on layout for my list-view and i am not able to get the item from the first text view in the onListItemClick method.
How can I achieve achievement this?
Layout of the ListView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/outputlayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#color/ligthgrey">
<TextView
android:id="#+id/txOutputDeparture"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Abfahrt "
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:maxLength="#android:integer/config_shortAnimTime"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/txOutputDuration"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txOutputDeparture"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Dauer"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/txOutputTransition"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txOutputDuration"
android:text="Umstieg"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="5dp" />
</RelativeLayout>
Method where i create and fill the listView and its and ListActivity
public void getRoute() {
mdbH = new DatabaseHelperActivity(this);
cursor = mdbH.fetchallRoutes(intent.getStringExtra("StartHaltestelle"),intent.getStringExtra("ZielHaltestelle"), intent.getStringExtra("Zeit"));
ArrayList<DefineRouteActivity> route = new ArrayList<DefineRouteActivity>();
while(cursor.moveToNext()) {
route.add(new DefineRouteActivity(cursor.getString(0),cursor.getString(2),cursor.getString(4)));
}
ArrayAdapter<DefineRouteActivity> adapter = new RouteAdapterActivity(this, route);
setListAdapter(adapter);
}
AdapterActivity:
Activity context;
ArrayList<DefineRouteActivity> arraylist;
public RouteAdapterActivity(Activity context, ArrayList list) {
super(context,R.layout.outputlayout,list);
this.context = context;
arraylist = list;
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View contentview, ViewGroup viewGroup) {
DefineRouteActivity routeItems = arraylist.get(position);
LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.outputlayout,null);
TextView tvDeparture = (TextView)view.findViewById(R.id.txOutputDeparture);
tvDeparture.setText(routeItems.getAbfahrtszeit());
TextView tvDuration = (TextView)view.findViewById(R.id.txOutputDuration);
tvDuration.setText(routeItems.getDauer());
TextView tvTransition = (TextView)view.findViewById(R.id.txOutputTransition);
tvTransition.setText(routeItems.getUmstieg());
return view;
}
Here is my onClick Method:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
((View)v).
Intent detail = new Intent(getApplicationContext(),DetailOutputActivity.class);
detail.putExtra("StartStop",l.getItemAtPosition(0).toString());
detail.putExtra("EndStop","ich");
detail.putExtra("Time","du");
detail.putExtra("Route","er");
startActivity(detail);
}
Here is my Layout containing the listView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
You need another xml containing the listView.
For example: sample.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
In your mainActivity.java:
setContentView(R.layout.sample.xml);
lv = (ListView)findViewById(R.id.lv1);
lv.setOnItemClickListener(this);
Your listActivity must implement OnItemClickListener.
Then implements onItemClick method. Example:
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// TODO Auto-generated method stub
int id_object = ((object)a.getAdapter().getItem(position)).getIdInstalacion();
Intent i = new Intent(this, Other.class);
i.putExtra("id_", id_object);
startActivity(i);
}

ListView.onItemClick not working

My ListView in Activity:
ListView listView1 = (ListView) menu.findViewById(R.id.menuList);
String menuItems[] = new String[] { "My Wants", "Profile", "Notifications",
"Feedback", "Logout" };
listView1.setAdapter(new SideMenuAdapter(this, menuItems, listView1));
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 1) {
Intent intent = new Intent(FeedListViewActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
if (position == 0) {
showMyWants();
}
}
});
menu is :
menu = inflater.inflate(R.layout.horz_scroll_menu, null);
horz_scroll_menu.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu"
android:layout_width="1dp"
android:layout_height="1dp"
android:background="#FFFFFFFF"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FF000000"
android:text="Menu"
android:textColor="#FFFFFFFF"
android:gravity="center" />
<ListView
android:id="#+id/menuList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#FFFFFFFF"
android:scrollbars="none" >
</ListView>
</LinearLayout>
My SideMenuAdapter:
public class SideMenuAdapter extends BaseAdapter {
private static final int TYPE_MAX_COUNT = 2;
private static LayoutInflater inflater = null;
private Activity activity;
public ImageLoader imageLoader;
public static String[] values;
ListView myList;
public SideMenuAdapter(Activity a, String[] sa, ListView lv) {
values = sa;
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myList = lv;
}
public int getCount() {
return values.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView mainText;
public TextView sideText;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View vi = convertView;
LayoutInflater inflater = activity.getLayoutInflater();
vi = inflater.inflate(R.layout.side_menu_list_item, null);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
vi.setTag(holder);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
holder.mainText.setText(values[position]);
if (position == 2) {
holder.sideText.setText("3");
holder.sideText.setBackgroundResource(R.drawable.orange);
}
return vi;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
}
My Xml for ListView items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sideMenuListItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="3dp" >
<TextView
android:id="#+id/sideText_sideMenu"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:gravity="center"
android:textSize="20dp"
android:padding="5dp" />
<TextView
android:id="#+id/mainText_sideMenu"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/sideText_sideMenu"
android:clickable="true"
android:gravity="left|center_vertical"
android:textSize="20dp"
android:padding="5dp" />
</RelativeLayout>
when running this application on Emulator, if i click with mouse nothing happens. But when i select any item on the list using navigation buttons on the KeyBoard and click Enter, it works fine.
when running the app on a device. If i go on click any item of the list, like some 10-20 times it works sometimes.
Edit:
Actually everything worked fine when i was using predefined ArrayAdapter<String> and android.R.simple_list_item. But i want a custom adapter
why is it so?
Its because in my ListView item layout i added
android:clickable="true"
for both the TextViews. So when i click on the ListView item it indeed is a click on these TextView whose onClick is not implemented. Removing the clickable attribute from the TextViews solved my problem.
Thanks everyone
Try making the RelativeLayout clickable and focusable.
Layout File
<ListView android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000fff"
android:layout_weight="2"
android:drawSelectorOnTop="false">
</ListView>
Main Activity
public class MyListView extends ListActivity {
/** 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, PENS));
getListView().setTextFilterEnabled(true);
}
static final String[] PENS = new String[]{
"MONT Blanc",
"Gucci",
"Parker",
"Sailor",
"Porsche Design",
"Rotring",
"Sheaffer",
"Waterman"
};
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, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
}
try this one
http://www.mkyong.com/android/android-listview-example/
res/layout/list_fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
ListView
public class ListFruitActivity extends ListActivity {
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no more this
// setContentView(R.layout.list_fruit);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,FRUITS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources