Android - Multiple selection in ListView - android

Okay, I am stuck whole day trying to get Checkbox added in listview. I have two part
If I click on any item in the listbox, it will load something (this part is already implemented).
There is a checkbox with each item. I want to be able to check any 10 or whatever number of items so that even if I scroll through the list, the selection will not get lost.
Can anyone please help me regarding that? One of the solution I checked is this solution, but I don't want to restructure whole code unless it is necessary.
MAINACTIVITY:
public class ShowList extends Activity{
static final String LIST_KEY_ID = "bookid";
static final String LIST_KEY_NAME = "bookname";
static final String LIST_KEY_WRITER = "writer";
ListView list;
MylibmanList adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_list);
setupActionBar();
mylibmandbhandler db = new mylibmandbhandler(this);
List<mylibman> allfld = db.getAllRecord();
db.close();
ArrayList<HashMap<String, String>> allbookList = new ArrayList<HashMap<String, String>>();
for (mylibman cn : allfld) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(LIST_KEY_ID, Integer.toString(cn.getBookid()));
map.put(LIST_KEY_NAME, cn.getBookname());
map.put(LIST_KEY_WRITER, cn.getWriter());
allbookList.add(map);
}
list=(ListView)findViewById(R.id.list);
adapter=new MylibmanList(this, allbookList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
batchid.clear();
HashMap<String, String> list_hashMap = (HashMap<String, String>) parent.getItemAtPosition(position);
String currlist = list_hashMap.get(LIST_KEY_ID);
Intent returnIntent = new Intent();
returnIntent.putExtra("bookid",currlist);
setResult(RESULT_OK,returnIntent );
finish();
}
});
ADAPTER CLASS:
public class MylibmanList extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public MylibmanList(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
TextView title;
TextView artist;
TextView duration;
CheckBox check;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow_row, null);
ViewHolder holder = new ViewHolder();
holder.title = (TextView)vi.findViewById(R.id.title);
holder.artist = (TextView)vi.findViewById(R.id.artist);
holder.duration = (TextView)vi.findViewById(R.id.duration);
holder.check = (CheckBox)vi.findViewById(R.id.check);
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("test","t3"); // Don't know what to do
}
});
vi.setTag(holder);
holder.check.setTag(data.get(position));
HashMap<String, String> book = new HashMap<String, String>();
book = data.get(position);
ViewHolder holderfin = (ViewHolder) vi.getTag();
holderfin.title.setText(book.get(ShowList.LIST_KEY_NAME));
holderfin.artist.setText(book.get(ShowList.LIST_KEY_WRITER));
holderfin.duration.setText(book.get(ShowList.LIST_KEY_ID));
holderfin.check.setChecked(false);
return vi;
}
}
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:orientation="horizontal"
android:padding="5dip" >
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:background="#drawable/image_bg"
android:layout_marginRight="5dip">
<!--
<ImageView
android:id="#+id/list_image"
android:contentDescription="#string/bookimage"
android:layout_width="50dip"
android:layout_height="50dip"/>
-->
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:textColor="#040404"
android:typeface="sans"
android:textSize="18sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/artist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:textColor="#343434"
android:textSize="13sp"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<TextView
android:id="#+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/title"
android:gravity="right"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:layout_marginRight="5dip"
android:textSize="12sp"
android:textColor="#10bcc9"
android:textStyle="bold"/>
<CheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:focusable="false"
android:layout_marginRight="10dp" />
</RelativeLayout>

Basically, you can have a hashset that contains only the selected items. The code would look like this
public class MylibmanList extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
HashSet<String> selectedBooks = new HashSet<String>();
//This listener will be used on all your checkboxes, there's no need to
//create a listener for every checkbox.
CompoundButton.OnCheckedChangeListener checkChangedListener = new CompoundButton.OnCheckedChangeListener{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String bookDuration = (String) buttonView.getTag();
if(isChecked){
selectedBooks.add(bookDuration);
}else{
selectedBooks.remove(bookDuration);
}
}
}
public MylibmanList(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
TextView title;
TextView artist;
TextView duration;
CheckBox check;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
convertView = inflater.inflate(R.layout.listrow_row, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.artist = (TextView) convertView.findViewById(R.id.artist);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.check = (CheckBox) convertView.findViewById(R.id.check);
holder.check.setOnCheckedChangeListener(checkChangedListener);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> book = new HashMap<String, String>();
book = (HashMap<String, String>) getItem(position);
holder.check.setTag(book.get(ShowList.LIST_KEY_ID));
holder.title.setText(book.get(ShowList.LIST_KEY_NAME));
holder.artist.setText(book.get(ShowList.LIST_KEY_WRITER));
holder.duration.setText(book.get(ShowList.LIST_KEY_ID));
boolean bookSelected = false;
if(selectedBooks.contains(book.get(ShowList.LIST_KEY_ID))){
bookSelected = true;
}
holder.check.setChecked(bookSelected);
return convertView;
}
I've changed your getView abit. The viewHolder will now be created only once for each view (as it should). Also, if its not too much of a hustle, you should create a class for your book. Something like
Class Book{
String title;
String artist;
Long duration;
}

Related

textview of listview in android

I have Listview that contains a Textview, I populate data from sqlite inside them , now I want to change the textview background color for each row based on the value in each one.
I couldn't do it , can anybody help me for how to get each textview from the listview ??
Edit :
Here is my code to populate the listview:
sql = new SqlCommands(getApplicationContext());
Fields = new String[]{SqlCommands.Group, SqlCommands.Subject, SqlCommands.Body, SqlCommands.DateTime};
int [] Dview = new int []{R.id.grop, R.id.sbj,R.id.bdy,R.id.DT};
Cursor c = sql.GetData();
Adpt = new SimpleCursorAdapter(getApplicationContext(),R.layout.items, c , Fields, Dview ,0 );
NotiLst.setAdapter(Adpt);
this is the XML file for the items :
<?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:orientation="horizontal"
android:background="#drawable/grp_shap" >
<ImageView android:id="#+id/Prio"
android:layout_width="32dip"
android:layout_height="32dip"
/>
<TextView
android:id="#+id/grop"
android:layout_width="64sp"
android:layout_height="40sp"
android:layout_alignBottom="#+id/Prio"
android:layout_alignParentLeft="true"
android:text="S"
android:textSize="12sp" />
<TextView
android:id="#+id/DT"
android:layout_width="wrap_content"
android:layout_height="14sp"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/title"
android:gravity="right"
android:text="Date Rec"
android:layout_marginRight="5dip"
android:textSize="12sp"
/>
<TextView
android:id="#+id/bdy"
android:layout_width="fill_parent"
android:layout_height="28sp"
android:layout_below="#+id/DT"
android:layout_toLeftOf="#+id/hi"
android:layout_toRightOf="#+id/Prio"
android:text="Body"
android:textSize="12sp" />
<TextView
android:id="#+id/sbj"
android:layout_width="fill_parent"
android:layout_height="12sp"
android:layout_alignLeft="#+id/bdy"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/bdy"
android:fontFamily="sans-serif"
android:text="Subject"
android:textSize="12sp" />
<ImageView
android:id="#+id/hi"
android:layout_width="20dip"
android:layout_height="26dip"
android:layout_alignLeft="#+id/DT"
android:layout_below="#+id/DT"
android:layout_marginLeft="15dp"
android:src="#drawable/highprio" />
</RelativeLayout>
and I have a listview on the activity_mail layout which populated whith this items.
I want to change the color for the textview with id grop based on the value inserted on it
You should use a custom adapter:
public class MyAdapter extends BaseAdapter {
private static class ViewHolder {
public final TextView mTv;
}
private final Context mContext;
private final List<String> mList; //you can change this to String array
public MyAdapter (Context context, List<String> list) {
this.mContext = context;
this.mList= list;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public String getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder h;
final String string = mList.get(position);
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.item_listview, null);
h = new ViewHolder();
h.mTv= (TextView) convertView .findViewById(R.id.mTvRes);
convertView.setTag(h);
} else {
h = (ViewHolder) convertView.getTag();
}
h.mTv.setText....
h.mTv.setTextColor....
h.mTv.setBackground....
return convertView;
}
}
in your activity:
List<String> list = Arrays.asList(Fields);
MyAdapter adapter = new MyAdapter(this, list);
NotiLst.setAdapter(adapter);
I didn't checked it and you maybe need to do some changes but it should work.
If you have something like this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(resource, parent, false);
viewHolder = new ViewHolder();
viewHolder.label = (TextView) convertView.findViewById(android.R.id.text1);
viewHolder.label.setBackground(getResources().getColor(color.white));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.label.setText(activitiesList.get(position).getName());
return convertView;
}

ImageView size issue within ListView

I encounter an error where when I first load a listview with images from a URL the size is not displayed correctly. However this only happens the first time.
If I go back to the previous fragment and then again to the ListView, the image sizes are fixed ( although I can see that momentarily they had the wrong size before being fixed ).
I use Android Query to retrieve the images and this example for my listview :
http://javatechig.com/android/android-listview-tutorial
SearchResultAdapter.java
public class SearchResultAdapter extends BaseAdapter{
private Context context;
private ArrayList listData;
private LayoutInflater layoutInflater;
public SearchResultAdapter(Context context, ArrayList listData) {
this.context = context;
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.searchresult_single_item, null);
holder = new ViewHolder();
holder.adImage = (ImageView) convertView.findViewById(R.id.adImage);
holder.adTitle = (TextView) convertView.findViewById(R.id.adTitle);
holder.adPrice = (TextView) convertView.findViewById(R.id.adPrice);
holder.adSize = (TextView) convertView.findViewById(R.id.adSize);
holder.adDetails = (TextView) convertView.findViewById(R.id.adDetails);
holder.adMessage = (ImageView) convertView.findViewById(R.id.adMessage);
holder.adFavorite = (ImageView) convertView.findViewById(R.id.adFavorite);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AdItem adListItem = (AdItem) listData.get(position);
AQuery aq = new AQuery(convertView);
aq.id(holder.adImage).image(adListItem.getAdImageURL(), true, true, 50, 0, null, AQuery.FADE_IN_NETWORK, 1.0f);
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(adListItem.getAdImageURL(), holder.adImage);
holder.adTitle.setText(adListItem.getAdTitle());
holder.adPrice.setText(adListItem.getAdPrice());
holder.adSize.setText(adListItem.getAdSize());
holder.adDetails.setText(adListItem.getAdDetails());
return convertView;
}
static class ViewHolder {
ImageView adImage;
TextView adTitle;
TextView adPrice;
TextView adSize;
TextView adDetails;
ImageView adMessage;
ImageView adFavorite;
}
}
SearchResultFragment.java
public class SearchResultFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_searchresult, container, false);
ArrayList listData = getListData();
final ListView searchResult = (ListView) view.findViewById(R.id.listViewSearchResult);
searchResult.setAdapter(new SearchResultAdapter(getActivity(), listData));
searchResult.invalidateViews();
return view;
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
AdItem adData = new AdItem();
adData.setAdImageURL("https://img.wg-gesucht.de/media/up/2014/36/3d3eb5b646560480_2014_09_07_19_26_33.sized.jpg");
adData.setAdTitle("Apartment");
adData.setAdPrice("€300");
adData.setAdSize("37m");
adData.setAdDetails("This is a wonderful apartment at a very reasonable price.");
results.add(adData);
adData = new AdItem();
adData.setAdImageURL("https://img.wg-gesucht.de/media/up/2014/46/a37ed74847504440_img_7409.sized.jpg");
adData.setAdTitle("Apartment");
adData.setAdPrice("€450");
adData.setAdSize("50m");
adData.setAdDetails("This is a wonderful apartment at a very reasonable price.");
results.add(adData);
adData = new AdItem();
adData.setAdImageURL("https://img.wg-gesucht.de/media/up/2014/46/4399903447385080_img_3106.sized.jpg");
adData.setAdTitle("Apartment");
adData.setAdPrice("€500");
adData.setAdSize("62m");
adData.setAdDetails("This is a wonderful apartment at a very reasonable price.");
results.add(adData);
return results;
}
}
This is my fragment layout for the row item :
<ImageView
android:id="#+id/adImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:minWidth="50dp"
android:minHeight="50dp"
android:layout_marginRight="20dp"/>
<TextView
android:id="#+id/adTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/adImage" />
<TextView
android:id="#+id/adPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="#id/adTitle"
android:layout_toRightOf="#id/adImage" />
<TextView
android:id="#+id/adSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="#id/adTitle"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/adPrice" />
<TextView
android:id="#+id/adDetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_toRightOf="#id/adImage"
android:layout_below="#id/adPrice"/>
<ImageView
android:id="#+id/adFavorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
<ImageView
android:id="#+id/adMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/adFavorite"/>
First image is what it looks like the first time the listview is loaded and what it looks like after ( 2nd image is what it should look like ).
If it is not necessary to keep this min width/height, you can get 2nd image result changing ImageView attributes in your list row to:
<ImageView
android:id="#+id/adImage"
android:layout_width="70dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:scaleType="centerCrop"/>

CustomListViewAdapter - Button click to affect TextView outside of ListView

I have a layout which consist of a ListView and a TextView.
On the ListView items, it has one Button. On the Button's onClickListener, is it able to change the text of the TextView that is on the parent layout?
I have set the Button's onClickListener but have not been able to find a way to let the Button change the TextView properties etc.
Thanks! :)
Layout:
// try this way,hope this will help you..
**XML** code
**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="match_parent"
android:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/txtChnageTextColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Android Demo Text For TextView"/>
<ListView
android:id="#+id/lstChangeTextColor"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"/>
</LinearLayout>
**list_item**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txtColor"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="16sp"/>
<Button
android:id="#+id/btnSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"/>
</LinearLayout>
**ACTIVITY** code
**MyActivity**
public class MyActivity extends Activity{
private ListView lstChangeTextColor;
private TextView txtChnageTextColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
lstChangeTextColor = (ListView) findViewById(R.id.lstChangeTextColor);
txtChnageTextColor = (TextView) findViewById(R.id.txtChnageTextColor);
ArrayList<HashMap<String,String>> listItem = new ArrayList<HashMap<String,String>>();
HashMap<String,String> map1 = new HashMap<String, String>();
map1.put("name", "Red");
map1.put("value", "#FF0000");
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("name", "Orange");
map2.put("value", "#FFA500");
HashMap<String,String> map3 = new HashMap<String, String>();
map3.put("name", "Yellow");
map3.put("value", "#FFFF00");
HashMap<String,String> map4 = new HashMap<String, String>();
map4.put("name", "Lime");
map4.put("value", "#00FF00");
HashMap<String,String> map5 = new HashMap<String, String>();
map5.put("name", "Blue");
map5.put("value", "#0000FF");
listItem.add(map1);
listItem.add(map2);
listItem.add(map3);
listItem.add(map4);
listItem.add(map5);
lstChangeTextColor.setAdapter(new ListAdapter(this,listItem));
}
class ListAdapter extends BaseAdapter{
private ArrayList<HashMap<String,String>> listItem;
private Context context;
public ListAdapter (Context context,ArrayList<HashMap<String,String>> listItem) {
this.listItem = listItem;
this.context = context;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return listItem.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item,null,false);
holder.txtColor = (TextView) convertView.findViewById(R.id.txtColor);
holder.btnSet = (Button) convertView.findViewById(R.id.btnSet);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtColor.setText(listItem.get(position).get("name"));
holder.btnSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(new Runnable() {
#Override
public void run() {
txtChnageTextColor.setTextColor(Color.parseColor(listItem.get(position).get("value")));
}
});
}
});
return convertView;
}
}
class ViewHolder{
Button btnSet;
TextView txtColor;
}
}

Assign onClick event for Button in list item of ListView

I have created a ListView that is populated from a database.Each row has a button to update the item value from the list and the database.I want to add onClick event for buttons used in item of ListView. How can I assign an OnClickListener for buttons for list items ?
addtooutlet.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:background="#ffffff">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
addtooutlet_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="5dip" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="46dp"
android:background="#ffffff"
android:padding="5dip"
android:weightSum="100" >
<TextView
android:id="#+id/item_bname"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="25"
android:padding="2dp"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip" />
<TextView
android:id="#+id/item_bid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="25"
android:padding="2dp"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip" />
<Button
android:id="#+id/item_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/item_bname"
android:layout_marginRight="16dp"
android:layout_weight="50"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="2dp"
android:text="Join"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textSize="12dip" />
</LinearLayout>
</LinearLayout>
AddTooutlet.java
public class AddToOutlet extends ListActivity {
SessionManager session;
String success, cus_id, bus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtooutlet);
session = new SessionManager(getApplicationContext());
session.checkLoginback();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// ID
final String cus_id = user.get(SessionManager.KEY_ID);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("cus_id", cus_id));
String response = null;
try {
response=LoginHttpClient.executeHttpPost("http://10.0.2.2/android_api/add_to_outlet.php",postParameters);
JSONObject json = new JSONObject(response);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
map.put("bus_name", json_data.getString("bus_name"));
map.put("bus_id", json_data.getString("bus_id"));
success = json_data.getString("success");
mylist.add(map);
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.addtooutlet_list_item, new String[] { "bus_name",
"bus_id" },
new int[] { R.id.item_bname, R.id.item_bid });
setListAdapter(adapter);
}
public class Myadapter extends ArrayAdapter<String> {
private OnClickListener callback;
public Myadapter(Context context, int resource, int textViewResourceId,
String[] strings, OnClickListener callback) {
super(context, resource, textViewResourceId, strings);
this.callback = callback;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.addtooutlet_list_item, parent,
false);
Button buttonEdit = (Button) row.findViewById(R.id.item_button);
buttonEdit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("xx", "Button pressed!");
}
});
return convertView;
}
private LayoutInflater getLayoutInflater() {
// TODO Auto-generated method stub
return null;
}
}
}
You have
View row = inflater.inflate(R.layout.addtooutlet_list_item, parent,
false);
But you return
return convertView;
Should be
View convertView = inflater.inflate(R.layout.addtooutlet_list_item, parent,
false);
And
Button buttonEdit = (Button) convertView.findViewById(R.id.item_button);
And
return convertView;
Edit:
As suggested in the comment by blackbelt. You are not using Custom ArrayAdapter
You probably meant
Myadapter adapter = new MyAdapter(ActivityName.this,R.layout.addtooutlet_list_item,mylist);
setListAdapter(adapter);
Then
ArrayList<HashMap<String,String> map;
LayoutInflater mInflater;
public Myadapter(Context context, int resource, int textViewResourceId,
ArrayLsit<HashMap<String,String> map, OnClickListener callback) {
super(context, resource, textViewResourceId, map);
this.map = map;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView ==null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.addtooutlet_list_item, parent,
false);
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.b = (Button) convertView.findViewById(R.id.item_button);
convertView.setTaf(holder);
}else{
holder =(ViewHolder) convertView.getTag();
}
HashMap<String,String> hm = map.get(position);
holder.tv1.setText(hm.get(postion).get("bus_name").toString());
holder.tv2.setText(hm.get(postion).get("bus_id").toString());
holder.b.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.i("xx", "Button pressed!");
}
});
return convertView;
}
The ViewHodler
static class ViewHolder
{
Button b;
TextView tv1,tv2;
}
Now you should have a textview's in layout.addtooutlet_list_item.xml and update views in getView.
Also consider using a ViewHolder Pattern
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

How to get checked items from a custom adapter?

The listview I used has custom xml and adapter. I want to get the checked items from this listview from anywhere. My xml is here:
<?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="wrap_content" >
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingBottom="30dp"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textStyle="bold"
android:paddingTop="15dp"
android:paddingRight="15dp"
android:paddingLeft="50dp"
android:text="Item" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:paddingRight="15dp"
android:paddingBottom="15dp"
android:paddingLeft="50dp"
android:text="Subtitle"
android:layout_below="#+id/text" />
</RelativeLayout>
My adapter is here:
private final List<Model> list;
private final List<Model> list2;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public Adapter(Activity context, List<Model> list, List<Model> list2) {
super(context, R.layout.listview, list);
this.context = context;
this.list = list;
this.list2 = list2;
}
static class ViewHolder {
protected TextView text;
protected TextView text2;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.text);
viewHolder.text2 = (TextView) convertView.findViewById(R.id.text2);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cb);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).sec(buttonView.isChecked());
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.text, viewHolder.text);
convertView.setTag(R.id.text2, viewHolder.text2);
convertView.setTag(R.id.cb, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position);
viewHolder.text.setText(list.get(position).isimGetir());
viewHolder.text2.setText(list2.get(position).isimGetir());
viewHolder.checkbox.setChecked(list.get(position).secilimi());
return convertView;
}
My aim is that getting checked items from a method placed in Main activity. However I cannot catch the values of checkboxes because of they're custom.
An approach you might use is to keep track of the checked items in the main activity by calling back to the main activity via intent or public method to maintain a list of them. Add and remove as the checked condition changes. You can fire off the intent or method whenever the checked value changes or on load in the adapter.

Categories

Resources