Android custom listview not clickable on item select - android

I am working with custom listView in android. but I cant able click the item in listview.
my code is
Adapter code(BankArrayListAdapter.java)
package com.example.customlist;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.method.LinkMovementMethod;
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 BankArrayListAdapter extends ArrayAdapter<Bank>{
private int resource;
private LayoutInflater inflater;
private Context ctx;
public BankArrayListAdapter(Context context, int resourceId, List<com.example.customlist.Bank> ls)
{
super(context, resourceId, ls);
resource = resourceId;
inflater = LayoutInflater.from( context );
ctx=context;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
/* create a new view of my layout and inflate it in the row */
convertView = inflater.inflate( resource, null );
/* Extract the city's object to show */
Bank bank = (Bank) getItem(position);
/* Take the TextView from layout and set the city's name */
TextView txtName = (TextView) convertView.findViewById(R.id.textView1);
txtName.setText(bank.getName());
/* Take the TextView from layout and set the city's wiki link */
TextView txtWiki = (TextView) convertView.findViewById(R.id.textView2);
txtWiki.setTextSize(13);
txtWiki.setMovementMethod(LinkMovementMethod.getInstance());
txtWiki.setText(bank.getUrl());
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) convertView.findViewById(R.id.imageView1);
String uri = "drawable/" + bank.getLogo();
int imageResource = ctx.getResources().getIdentifier(uri, null, ctx.getPackageName());
Drawable image = ctx.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
package com.example.customlist;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
ListView lv;
List<Bank> ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
ls= new ArrayList<Bank>();
ls.add(new Bank("sbi","State Bank Of India","http://www.sbi.com"));
ls.add(new Bank("iob", "India Overseas Bank","http://www.iob.com"));
ls.add(new Bank("icici","ICICI","http://www.icici.com"));
//lv.setAdapter( new BankArraylistA);
lv.setAdapter( new BankArrayListAdapter(Main.this, R.layout.banklist, ls ) );
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(Main.this,"Your Listener Works!",Toast.LENGTH_SHORT).show();
// System.out.println("Name: "+ls.get(position).getName());
// String s =(String) ((TextView) v.findViewById(R.id.From)).getText();
// Toast.makeText(Messages.this, s, Toast.LENGTH_LONG).show();
}
});
System.out.println(ls);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml file goes like this
<LinearLayout 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:descendantFocusability="blocksDescendants"
tools:context=".Main" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Thanks in advance
Regards,
Sathish

I had the same problem and I solved by add this code to getView() method in my custom adapter class, yours BankArrayListAdapter.java
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.v("LV_ITEM", "Position of item is " + position);
}
});

Related

Change color and size of Textview in custom Listview having custom adapter and custom layout file

I am having problem with changing color of Textview in custom Listview.
My xml file is column.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textSize="30dp"
android:visibility="gone"/>
<TextView
android:id="#+id/cname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25dp"
android:textColor="#f60505" />
<TextView
android:id="#+id/amt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#2ec31d"
android:textAlignment="center" />
</LinearLayout>
and ListViewAdapter.java goes like this
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by XYZ on 06-05-2016.
*/
public class ListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String,String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String,String>>list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.colunm_row,null);
holder = new ViewHolder();
holder.textFirst=(TextView)convertView.findViewById(R.id.cid);
holder.textSecond=(TextView)convertView.findViewById(R.id.cname);
holder.textThird=(TextView)convertView.findViewById(R.id.amt);
txtFirst = (TextView) convertView.findViewById(R.id.cid);
txtSecond = (TextView)convertView.findViewById(R.id.cname);
txtThird = (TextView) convertView.findViewById(R.id.amt);
convertView.setTag(holder);
}else {
holder =(ViewHolder)convertView.getTag();
holder.textFirst.setText("");
holder.textSecond.setText("");
holder.textThird.setText("");
}
HashMap<String,String> map= list.get(position);
/* txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));*/
holder.textFirst.setText(map.get(FIRST_COLUMN));
holder.textSecond.setText(map.get(SECOND_COLUMN));
holder.textThird.setText(map.get(THIRD_COLUMN));
return convertView;
}
static class ViewHolder{
TextView textFirst;
TextView textSecond;
TextView textThird;
}
}
DisplayActivity :
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AccDisplay extends AppCompatActivity {
private ArrayList<HashMap<String,String>> arrayList;
Cursor c;
SQLiteDatabase db;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc_display);
ListView listView = (ListView)findViewById(R.id.AcclistView);
arrayList = new ArrayList<HashMap<String, String>>();
db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);
c=db.rawQuery("select c.c_id ,c.c_name, ((select CASE WHEN (sum(cr.amount)) IS Null THEN 0 ELSE sum(cr.amount) END from credit_master cr where c.c_id=cr.c_id) ) - ((select CASE WHEN (sum(d.amount)) IS NULL THEN 0 ELSE sum(d.amount) END from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c ORDER BY c.c_name ASC",null);
//c=db.rawQuery("select c.c_id ,c.c_name, ((select sum(cr.amount) from credit_master cr where c.c_id=cr.c_id) ) - ((select sum(d.amount) from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c",null);
try {
if (c!=null){
if(c.moveToFirst()){
Map<String,String> tem = new HashMap<String ,String>();
tem.clear();
arrayList.clear();
listView.setAdapter(null);
int cnt = c.getCount();
Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
do {
tem = new HashMap<String,String>();
tem.clear();
tem.put(FIRST_COLUMN, c.getString(0));
tem.put(SECOND_COLUMN,c.getString(1));
tem.put(THIRD_COLUMN,c.getString(2));
arrayList.add((HashMap<String, String>) tem);
}while (c.moveToNext());
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) (view.findViewById(R.id.cid));
int str = Integer.parseInt(tv.getText().toString());
Toast.makeText(AccDisplay.this,"Clicked"+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(AccDisplay.this,Details.class);
intent.putExtra("name",str);
startActivity(intent);
}
});
}
protected void onRestart(){
super.onRestart();
Intent inte = getIntent();
finish();
startActivity(inte);
}
}
I am using same layout file for three different activities.
I want to display different color of each TextView in Different Activity.
I have tried this but didn't work
LayoutInflator inflator = (LayoutInflator)getSystemService(Context.LAYOUT_INFLATOR_SERVICE);
View vi = inflator.inflate(R.layout.column,null);
TextView tv = (TextView) vi.findViewById(R.id.amt);
tv.setTextColor(Color.BLACK);
I can change color of TextView in OnItemClickListener but i want to display color while displaying data.
I am having Debit/Credit activity which uses same Adapter class and column.xml layout for displaying data in listview.
I want to display TextView1 in black color font and TextView2 in Green color with big font size in Activity 1. and different color in different activity.
You can pass different flags in adapter constructor to adapter for identifying activity if same adapter you are using for other activities, and can put conditions according to the flag set colors to the TextView in adapter programmatically. textView.setTextColor(put_your_color);

get onclick for button in listview, in fragment

I have a listview with several buttons in which the button.text property populated with several child names from a an sqlite database.
I need to retrieve tasks specificaly assigned to each child when the child's button is clicked (possibly using the text property of the button(which is populated with the child name) ).
I have 3 java files that i am working (ChildDatabase, ChildListAdapter, ChildList) with and 2 xml files(fragment_child_list_layout, fragment_child_list).
Where can I set an onClick event for the buttons in my list view. And how can i differentiate from each button if only ONE BUTTON is delcared?
This is my ChildDatabase file
package com.example.victor.kidsrewards;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildDataBase {
private SQLiteDatabase db;
private ChildSQLiteHelper childSQLiteHelper;
String _parentName = Globals._username;
public ChildDataBase(Context context) {
childSQLiteHelper = new ChildSQLiteHelper(context);
db = childSQLiteHelper.getWritableDatabase();
}
public void Close() {
db.close();
}
public void createChild(String childNameText, String nickNameText, String genderText, int ageText) {
String query = "select * from child";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
ContentValues contentValues = new ContentValues();
contentValues.put("id", count);
contentValues.put("childname", childNameText);
contentValues.put("nickname", nickNameText);
contentValues.put("age", ageText);
contentValues.put("gender", genderText);
contentValues.put("parent", _parentName);
//insert
db.insert("child", null, contentValues);
}
public List<ChildUser> getChildren() {
List<ChildUser> childList = new ArrayList<ChildUser>();
//select columns
String[] tableColumns = new String[]{"id", "childname", "nickname"};
Cursor cursor = db.query("child", tableColumns, "parent =? ", new String[]{_parentName}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ChildUser child = new ChildUser();
//take values from database
child.setId(cursor.getInt(0));
child.setChildName(cursor.getString(1));
child.setNickName(cursor.getString(2));
//add to db
childList.add(child);
cursor.moveToNext();
}
return childList;
}
public String[] getChildNames() {
String[] tableColumns = new String[]{"childname"};
Cursor cursor = db.query("child", tableColumns, "parent =?", new String[]{_parentName}, null, null, null);
String[] array = new String[cursor.getCount()];//sets the length of the array
int i = 0;
while (cursor.moveToNext()) {
String uname = cursor.getString(cursor.getColumnIndex("childname"));
array[i] = uname;
i++;
}
return array;
}
}
This is my ChildListAdapter
Displays same button over again with different text property
package com.example.victor.kidsrewards;
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.List;
/**
* Created by Victor on 4/3/2016.
*/
public class ChildListAdapter extends ArrayAdapter<ChildUser> {
private final Context context;
private final List<ChildUser> childList;
public ChildListAdapter(Context context, List<ChildUser> childList){
super(context, R.layout.fragment_child_list_layout, childList);//fragment_child_list
this.context = context;
this.childList= childList;
}
#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.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
return rowView;
}
ChildList class
package com.example.victor.kidsrewards;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ChildList extends ListFragment {
private ChildDataBase cdb;
public ChildList() {
// Required empty public constructor
}
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_child_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
cdb = new ChildDataBase(getContext());
setListAdapter(new ChildListAdapter(getContext(), cdb.getChildren()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
}
fragment_child_list_layout.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/childButton"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
fragment_child_list.xml
<FrameLayout 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="com.example.victor.kidsrewards.ChildList">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:text="TODO TEXT GOES_HERE">
</ListView>
</FrameLayout>
You can set the OnClickListener for the Button inside the getView() method of the adapter. The position argument can be used to identify which button was clicked.
See the code,
#Override
public View getView(final int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String selectedChild = childList.get(position).getNickName();
// do something with selected item
}
});
return rowView;
}
#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.fragment_child_list_layout,parent,false);
Button childName = (Button)rowView.findViewById(R.id.childButton);
childName.setText(childList.get(position).getNickName());
childName.setOncLickListener(new OnclickListener() {
public void onClick() {
// do something for click each row
}
return rowView;
}

Not able to detect the button clicked on gridview

I am developing a simple calculator android app that will evaluate the expression and display the result in a textbox.But i am not able to detect the button clicks.I dont want to define my own Adapter.Check out my codes :
activity_main.xml :
<LinearLayout 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:orientation="vertical"
android:padding="30dp"
>
<EditText
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="#string/expression"
/>
<GridView
android:id="#+id/grid"
android:numColumns="4"
android:columnWidth="20dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="100dp"
></GridView>
</LinearLayout>
gridcontent.xml :
<?xml version="1.0" encoding="utf-8"?>
<Button
android:layout_width="70dp"
android:layout_height="70dp"
android:clickable="true"
xmlns:android="http://schemas.android.com/apk/res/android"/>
MainActivity.java :
package com.example.calculator;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Character> arr = new ArrayList<Character>();
String str = "789/456*123-.0=+";
for(int i = 0;i<str.length();i++)
arr.add(str.charAt(i));
ArrayAdapter<Character> adapter = new ArrayAdapter<>(this, R.layout.gridcontent, arr);
GridView grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, position + "done", Toast.LENGTH_SHORT).show();
}
});
}
}
Note : I am new to android and playing around with stuff :)
Thanks for your help in advance
Create Adapter for grid like
Class Gridlistadapter extends ArrayAdapter<Character>
{
public Gridlistadapter (Context context, int resource,
List<Character> objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.gridcontent, null);
}
Character data = getItem(position);
Button button1= (Button) view.findViewById(R.id.button1);
button1.setText(""+data);
button1.setOnClickListener(new Listener(position));
return view;
}
class listener implements OnClickListener {
private int position;
listener(int position) {
this.position = position;
}
#SuppressLint("UseValueOf")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, position + "done", Toast.LENGTH_SHORT).show();
}
}
}
}
package com.example.calculator;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Character> arr = new ArrayList<Character>();
String str = "789/456*123-.0=+";
for(int i = 0;i<str.length();i++)
arr.add(str.charAt(i));
Gridlistadapter adapter = new Gridlistadapter (this, R.layout.gridcontent, arr);
GridView grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, position + "done", Toast.LENGTH_SHORT).show();
}
});
}
}

set a listener for widgets in items of a listview

I meet a problem developing an android project.
Using adapter, I place many items in a ListView, and there is an ImageButton in each item. Now I want to set a click listener for these ImageButtons. What should I do?
This achieves your desired result. Its functionality is the button itself has a click response different from the container, which also has a response.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Toast.makeText( MainActivity.this,
"List item clicked",
Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
items.add( "item3");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.List;
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
Toast.makeText( context,
"ImageButton clicked",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
item.xml
<?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="wrap_content"
android:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="28sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:src="#drawable/emo_im_cool" />
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list" />
Try it out and hopefully you can see what's going on to learn what you need

Android checkbox issue in custom list item view

Please forgive me for what may sound like a newbie question as I am just getting started
with Android.
What I am attempting to accomplish is creating a custom list Item layout that contains 2 textViews and a checkbox for selecting multiple items. The problem is the checkboxes are
"extra" selecting list items, (example) if I select #1 then #9 and # 18 selects as well.
as if the checkBox instances are recycling themselves or maybe sharing the same listener IDs
if that even makes sense. Ive narrowed my code to the primary components for simplicity. Any suggestions would be dearly appreciated.
package com.untame.mobile.app;
import java.text.ChoiceFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.untame.mobile.app.*;
public class TestList extends ListActivity {
ArrayList<Map<String, String>> artistList;
private static String TAG = "TESTLIST!";
ListView listv;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlayout);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
artistList = new ArrayList<Map<String, String>>();
for(Integer loop = 0 ;loop < 21;loop++){
String loopI = loop.toString();
Map<String,String> hm = new HashMap<String, String>();
hm.put("artist", loopI);
hm.put("count", loopI);
artistList.add(hm);
}
// Loading artistNames in Background Thread
// new LoadArtistList().execute("extra_tracks");
listv = (ListView) getListView();
listv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// listv.setItemsCanFocus(false);
final class MyListAdapter extends BaseAdapter{
ArrayList<Integer> ids;
public MyListAdapter(Context context) {
ids = new ArrayList<Integer>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.testlistitem1, null, false);
convertView.setClickable(true);
holder = new ViewHolder(getApplicationContext());
holder.choose = (CheckBox) convertView.findViewById(R.id.testcheckBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return artistList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return artistList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
MyListAdapter adapter = new MyListAdapter(this);
setListAdapter(adapter);
}
}
ViewHolder.java
package com.untame.mobile.app;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class ViewHolder extends View {
public ViewHolder(Context context) {
super(context);
}
public CheckBox remove;
public CheckBox choose;
public TextView text2;
public TextView text1;
}
testlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
testitem.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" >
<com.untame.mobile.app.ArtistListCheckBox
android:id="#+id/testcheckBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose"
/>
</LinearLayout>
Solved!!! It appears after much trial and error, that one must store the actual checkbox information (ie : checkbox.isChecked) into a seperate object that can be stored as a tag inside the current checkbox. This way when the view redraws the new items as you scroll the
list the newly created checkbox can recapture its last state from the object it was stored in.
In my case, I have a list of Music Artists in the list so I created an Artist.java class
to create Artist objects to store as checkbox tags.

Categories

Resources