Custom ListView not being selected on click - android

So I have looked through a lot of other answers but have not been able to get my app to work how I want it. I basically want the list view that has the text and check mark to the right, but then an addition button to the left. Right now my list view shows up but the check image is never changed.
Edit: after a helpful comment I discovered that the rows can be selected by using the arrow (up/down) on the emulator, this highlights the row how I want. However, when I click the row it does not become selected like I want it to. Also, if it helps the list view is being used inside a dialog box.
Selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/accept_on" />
<item
android:drawable="#drawable/accept" />
</selector>
Row xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#EEE">
<ImageButton
android:id="#+id/goToMapButton"
android:src="#drawable/go_to_map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left" />
<TextView
android:id="#+id/itemName"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_weight="1" />
<Button
android:id="#+id/checkButton"
android:background="#drawable/item_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right" />
</LinearLayout>
MapAdapter:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MapAdapter extends ArrayAdapter<String>{
Context context;
int layoutResourceId;
String data[] = null;
LayoutInflater inflater;
LinearLayout layout;
public MapAdapter(Context context, int layoutResourceId, String[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
inflater = LayoutInflater.from(context);
}
#Override
public String getItem(int position) {
return data[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
if(convertView == null)
{
convertView = inflater.inflate(R.layout.map_item_row, null);
layout = (LinearLayout)convertView.findViewById(R.id.layout);
holder.map = (ImageButton)convertView.findViewById(R.id.goToMapButton);
holder.name = (TextView)convertView.findViewById(R.id.itemName);
//holder.check = (Button)convertView.findViewById(R.id.checkButton);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
layout.setBackgroundColor(0x00000004);
holder.name.setText(getItem(position));
return convertView;
}
static class ViewHolder
{
ImageButton map;
TextView name;
Button check;
}
}

Try by setting the selector as background instead of src

Try like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
Planet planet = (Planet) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new PlanetViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Planet planet = (Planet) cb.getTag();
planet.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
See this example http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php

Related

changing content of text view on button click inside listview

this is the image of layout tile.xml
i have created a list using custom adapter it has 2 textviews and 2 buttons inside it now what i want is to change the visiblity of one of textview on button click.
I am handling the button clicks outside the custom adapter.I want to toggle visiblity toggle for second textview with id tvstatus using on and off buttons.
this is code for customadapter
package slide.apptech.com.rpiconnect;
/**
* Created by MOHIT on 09-06-2016.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
//custom adapter class extends a arrayadapter
public class customadapter2 extends ArrayAdapter<String> {
private final Context context;
private final ArrayList values;
private String stv = "Ststus";
public customadapter2(Context context, ArrayList values) {
//for super constructor pass
// context files
//layout file required for list
//arraylist that has strings to be displayed
super(context, R.layout.tile, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewGroup par = parent;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.tile, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.tvappname);
Button on = (Button) rowView.findViewById(R.id.bon);
Button off = (Button) rowView.findViewById(R.id.boff);
final TextView status = (TextView) rowView.findViewById(R.id.tvstatus);
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status.setVisibility(View.VISIBLE);
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) ;
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
//get(position method is used to access the elements of arraylist)
String val = (String) values.get(position);
textView.setText(val);
// Change the icon for Windows and iPhone
String s = (String) values.get(position);
return rowView;
}
public void myClickHandler(View v)
{
}
}
this is code for my xml file that i am using as listelement
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_margin="2dp"
android:layout_height="100dp"
card_view:cardCornerRadius="4dp"
android:layout_alignParentStart="true"
android:background="#611818"
android:paddingBottom="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OFF"
android:id="#+id/boff"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginStart="37dp"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bon"
android:text="ON"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="28dp"
android:focusable="false"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ttile"
android:id="#+id/tvappname"
android:textSize="20sp"
android:layout_above="#+id/boff"
android:layout_centerHorizontal="true"
android:textColor="#color/abc_input_method_navigation_guard" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="#+id/tvstatus"
android:layout_below="#+id/tvappname"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textColor="#060505"
android:visibility="invisible"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
please comment if you want any other file
No, don't do that. Changing the value directly of any view inside listview is a bad idea. Just make changes in your arraylist and then call notifyDataSetChanged() to reflect changes.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewGroup par = parent;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.tile, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.tvappname);
Button on = (Button) rowView.findViewById(R.id.bon);
Button off = (Button) rowView.findViewById(R.id.boff);
final TextView status = (TextView) rowView.findViewById(R.id.tvstatus);
//get(position method is used to access the elements of arraylist)
String val = (String) values.get(position);
textView.setText(val);
if(val.equalsIgnoreCase("off")){
status.setVisibility(View.INVISIBLE);
}else{
status.setVisibility(View.VISIBLE);
}
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.set(position, "On");
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.set(position, "Off");
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
// Change the icon for Windows and iPhone
String s = (String) values.get(position);
return rowView;
}
Hope it will help :)

Editing ListView Text

I am working on an android app, currently i have following code:
<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:background="#drawable/background_main"
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" >
<TextView
android:id="#+id/display_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:textSize="20pt"
android:textColor="#FFFFFF"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp" >
</ListView>
</RelativeLayout>
and
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private TextView tv;
private MediaPlayer player = null;
ListView listV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.display_result);
listV = (ListView)findViewById(R.id.listView1);
final Intent i = new Intent(this,BActivity.class);
String[] values = new String[] { "C 2 F", "F 2 C", "Currency"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
listV.setAdapter(arrayAdapter);
listV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
if(itemPosition == 0)
{
i.putExtra("identify", "c2f");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
else if(itemPosition == 1)
{
i.putExtra("identify", "f2c");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
else if(itemPosition == 2)
{
i.putExtra("identify", "currency");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
}
});
}
protected void onDestroy()
{
super.onDestroy();
player.stop();
}
#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;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
tv.setVisibility(View.VISIBLE);
tv.setText(result);
player = MediaPlayer.create(this, R.raw.sound);
player.start();
}
}
}
}
It's all working well, but the ListView is showing very small black text alligned left, i want to change it to center and increase the size, also is there any simple way to include pictures along with text on the listview. I searched on it a lot but they are all extremely difficult to understand, kindly tell me what changes do i have to make in my code to be able to edit the listView text.
You need have another layout with TextView. Customize the below layout to suit your needs. You can increase the text size change the text color and customize the textview the way you want.
row.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="TextView" />
</RelativeLayout>
Then
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.row,R.id.textView1, values);
Snap
All the layout of the ListView is given by the Adapter. You're using the simple ArrayAdapter, with the simple_list_item_1 (that is a simple TextView).
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
The good: this is really easy, as you have seen.
The bad: you cannot do much except a list of strings.
If you want to include images, more TextViews or other nice things you will have to create a custom Adapter, overriding the ArrayAdapter or another one, as the BaseAdapter.
Here you can find a simple tutorial by Vogella.
As you can see all the work is done in the getView method, where all the "creation" takes place.
#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.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
At the beginning you will have to "inflate" (create) the row. From the row then you will "find" the views and set the items respectively on the position of the row.
Performance note:
since Android will recycle the rows, you should check if the line was already created. So just check, before the inflate and wrapping all the code, if the convertView is null or not.
Here is your row.xml with ImageView and TextView . It's a way your list items will look.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="#dimen/item_height"
android:layout_width="match_parent">
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_image"
android:layout_width="60dp"
android:layout_height="60dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/item_image"
android:id="#+id/item_label"/>
</RelativeLayout>
Then you need to create custom adapter, e.g. ArrayAdapter of String:
public class SampleAdapter extends ArrayAdapter<String> {
private LayoutInflater layoutInflater;
public SampleAdapter(Context context, ArrayList<String> data) {
super(context, R.layout.adapter_deals_list_fragment, data);
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
String item = getItem(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.row, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imageView.setImageDrawable(new ColorDrawable(Color.parseColor("#ffaa66cc")));
viewHolder.textView.setText(item);
return convertView;
}
private class ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(View view) {
imageView = (ImageView) view.findViewById(R.id.item_image);
textView = (TextView) view.findViewById(R.id.item_label);
}
}
}
After that do something like this in yout Activity class:
SampleAdapter sampleAdapter = new SampleAdapter(this, new String[]{"lorem", "ipsum", "dolar"});
ListView listView = (ListView) findViewById(R.id.listview1);
listView.setAdapter(sampleAdapter);
As result your ListView item will look like an Fill Colored Image and Text.

Get different multiple image views in a list view

I have been trying to implement a list view which has five image views in a single row of a list view. I found that it can be done with layout inflater but since I am new to android I could not exactly get how to make the best use of it. I want to get a view of this sort:
L,S,D,A,E are images and it should change accordingly for different users in the list view according to the data provided dynamically. Can anybody please help me with the code snippet for this, or just give me an idea on how to implement it?
Okay so your list view should inflate a layout of this type:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/layoutContainer" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv1" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv2" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv3" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv4" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv5" />
</LinearLayout>
Save it to row.xml located in your layout folder.
Next implement this in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter myAdapter = new CustomAdapter(getApplicationContext());
ListView mainListView = (ListView) findViewById(R.id.lv);
mainListView.setAdapter(myAdapter);
}
Finally, you need to create the CustomAdapter.java class, like this:
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class CustomAdapter extends BaseAdapter {
private Bitmap[][] data;
private int count;
private Context context;
public CustomAdapter(Context context) {
this.context = context;
data = new Bitmap[100][];
count = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public Bitmap[] getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View adapterView = convertView;
if (adapterView == null) {
adapterView = inflater.inflate(R.layout.row, null);
}
ImageView imageView = (ImageView) adapterView.findViewById(R.id.iv1);
imageView.setImageBitmap(data[position][0]);
//Repeat the last two steps for all five images, changing the last index accordingly
return adapterView;
}
public void addBitmapArray (Bitmap[] newValue) {
data[++count] = newValue;
}
}
In row of the list add a linear layout LinearLayout1 then do something like fallowing in your adapter add dynamically images to the list item..
public View getView(final int position, View convertView, ViewGroup parent)
{
// System.out.println(" inside KeyvalueAdapter..");
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.new_row, null);
holder = new ViewHolder();
holder.tv_title = (TextView) convertView.findViewById(R.id.titleTextView);
ImageView imageView = new ImageView(context);
imageView.setImageResource(resId);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearLayout.addView(imageView);
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
holder.tv_title.setText(notifList.get(position));
return convertView;
}
If you want to load different image you have to extend your listview adapter:
example if i understand correctly your question.
Check out this thread:
Android custom Row Item for ListView
You have to write your own xml with 5 imageviews

ExpandableListView CheckBox doesn't trigger onClick event

In my ExpandableListView, each child row contains a CheckBox and a TextView. Everything works perfectly (finally!) when I tap on the TextView. However, when I tap on the Checkbox, its state changes, but the onClick event never fires. There are no errors, but nothing really happens.
I want both the textview and the checkbox to invoke the same behavior (i.e. the user should be able to click anywhere on the row and the same behavior will result). What am I doing wrong? Thank you!
public class ExpandListAdapter extends BaseExpandableListAdapter {
public ExpandListAdapter(Context context, ArrayList<ExpandListGroup> groups) {
this.context = context;
this.groups = groups;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, final ViewGroup parent) {
view = getCategoryChildView(groupPosition, childPosition, view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this works for the textview click but
//doesn't fire when the check box is clicked
System.err.println("child clicked");
}
});
return view;
}
private View getCategoryChildView(int groupPosition, int childPosition, View view) {
ClientFinderCategories child = (ClientFinderCategories) getChild(groupPosition, childPosition);
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.expandlist_child_item_category, null);
holder.checkBox = (CheckBox) view.findViewById(R.id.check_box);
holder.textView = (TextView) view.findViewById(R.id.expand_list_item);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
try {
holder.checkBox.setChecked(child.getIsSelected());
holder.textView.setText(child.getCategory());
} catch (Exception e) {}
return view;
}
}
layout 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="55dip"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/check_box"
android:layout_marginLeft="30dp"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/expand_list_item"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/smart_finder_settings_font_size"
android:textColor="#FFFFFF" />
</LinearLayout>
If a view contained in another view (here: CheckBox in LinearLayout) handles a click itself (which CheckBox does whereas TextView was set android:clickable="false") then the OnClickListener of the containing view isn't called.
Call setOnCheckedChangeListener() on the CheckBox itself to install an appropriate listener.

Android ListView row color

I'm trying to change the row color of my listView in customAdapter. There's an array of integer that include 0 and 1, I'm trying to read from the array and change the color of rows like this:
0 = white
1 = yellow
but it shows a yellow color in all rows.
This is my CustomAdapter:
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<RowItem> {
ArrayList<Integer> test;
Context context;
public CustomAdapter(Context context, int resourceId, List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
SqliteHelper checkFav = new SqliteHelper(context);
checkFav.open();
test = checkFav.getFavForList();
checkFav.close();
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_layout, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.pTxt);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
int color0 = Color.YELLOW;
int colorDefault = Color.WHITE;
switch (test.get(position)){
case 0:
convertView.setBackgroundColor(colorDefault);
break;
case 1:
convertView.setBackgroundColor(color0);
}
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
And this is my row_layout.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="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/active_icon" />
<TextView
android:id="#+id/pTxt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="20sp"
android:gravity="right"/>
</LinearLayout>
Thanks in advance.
getView() is called for each row in a list so you should not loop over all items in test but only handle the one denoted by position and you should do that after (not in) the if (convertView == null) block.
Edit:
getView() should do the following things:
Check if convertView isn't null (if it is, create a new View as you did)
Check if convertView is of the right type (this only matters if more than one kind of View is used in the list which is not the case here). If the type is wrong, create a new View.
Now we have a valid View for the list row.
Retrieve the data which affects how to display this row. In your case this would be the result of test.get(position). The position is the number of the requested row (starting with 0 at the top of the ListView).
Adjust the View according to your data (you did this in the for-loop but you should do it only once for the requested entry at position).
Return the View
In more complex situations you may have to do the third step before the second but not here.
Fast solution (not very nice code, but works):
#Override
public int getItem(int position){
return test.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int color0 = ....
int color1 = ....
int colorDefault = ...
switch (test.get(position)) {
case 0:
convretview.setBackgroundColor(color0);
break;
case 1:
convretview.setBackgroundColor(color1);
break;
default:
convretview.setBackgroundColor(colorDefault);
}
...
}

Categories

Resources