Can someone help me to do this please? i want to search item from listview using SearchView. Here's my code
This is the ListObat.java
package co.id.zsoft.apotikstore;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListObat extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_obat);
ArrayList<ItemDetails> image_details = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.listView);
lv1.setAdapter(new ItemListBaseAdapter(this, image_details));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
ItemDetails obj_itemDetails = (ItemDetails) o;
Toast.makeText(ListObat.this, "You have chosen : " + " " + obj_itemDetails.getName(), Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<ItemDetails> GetSearchResults(){
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
ItemDetails item_details = new ItemDetails();
item_details.setName("Pizza");
item_details.setItemDescription("Spicy Chiken Pizza");
item_details.setPrice("RS 310.00");
item_details.setImageNumber(1);
results.add(item_details);
item_details = new ItemDetails();
item_details.setName("Burger");
item_details.setItemDescription("Beef Burger");
item_details.setPrice("RS 350.00");
item_details.setImageNumber(2);
results.add(item_details);
item_details = new ItemDetails();
item_details.setName("Pizza");
item_details.setItemDescription("Chiken Pizza");
item_details.setPrice("RS 250.00");
item_details.setImageNumber(3);
results.add(item_details);
item_details = new ItemDetails();
item_details.setName("Burger");
item_details.setItemDescription("Chicken Burger");
item_details.setPrice("RS 350.00");
item_details.setImageNumber(4);
results.add(item_details);
item_details = new ItemDetails();
item_details.setName("Burger");
item_details.setItemDescription("Fish Burger");
item_details.setPrice("RS 310.00");
item_details.setImageNumber(5);
results.add(item_details);
item_details = new ItemDetails();
item_details.setName("Mango");
item_details.setItemDescription("Mango Juice");
item_details.setPrice("RS 250.00");
item_details.setImageNumber(6);
results.add(item_details);
return results;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_obat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the ItemDetails.java
package co.id.zsoft.apotikstore;
/**
* Created by rsr_unitedstate on 12/18/2015.
*/
public class ItemDetails {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getImageNumber() {
return imageNumber;
}
public void setImageNumber(int imageNumber) {
this.imageNumber = imageNumber;
}
private String name ;
private String itemDescription;
private String price;
private int imageNumber;
}
This is the ItemListBaseAdapter.java
package co.id.zsoft.apotikstore;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
/**
* Created by rsr_unitedstate on 12/18/2015.
*/
public class ItemListBaseAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsrrayList;
private Integer[] imgid = {
R.drawable.testimage,
R.drawable.testimage,
R.drawable.testimage,
R.drawable.testimage,
R.drawable.testimage,
R.drawable.testimage
};
private LayoutInflater l_Inflater;
public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.price);
holder.txt_itemPrice = (TextView) convertView.findViewById(R.id.price);
holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);
holder.txt_qty = (TextView) convertView.findViewById(R.id.Qty);
holder.btnkurang = (ImageButton) convertView.findViewById(R.id.btnkurang);
holder.btntambah = (ImageButton) convertView.findViewById(R.id.btntambah);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
holder.txt_itemDescription.setText(itemDetailsrrayList.get(position).getItemDescription());
holder.txt_itemPrice.setText(itemDetailsrrayList.get(position).getPrice());
holder.itemImage.setImageResource(imgid[itemDetailsrrayList.get(position).getImageNumber() - 1]);
// imageLoader.DisplayImage("http://192.168.1.28:8082/ANDROID/images/BEVE.jpeg", holder.itemImage);
return convertView;
}
static class ViewHolder {
TextView txt_itemName;
TextView txt_itemDescription;
TextView txt_itemPrice;
TextView txt_qty;
ImageView itemImage;
ImageButton btntambah;
ImageButton btnkurang;
}
}
This is the activity_list_obat.xml as listview layout
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="co.id.zsoft.apotikstore.ListObat">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/imageButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:id="#+id/listView"
android:layout_below="#+id/editText"
android:layout_alignParentEnd="true" />
</RelativeLayout>
And this is the item_details_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/photo"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Obat"
android:id="#+id/name"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/photo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Harga Obat"
android:id="#+id/price"
android:layout_below="#+id/name"
android:layout_toEndOf="#+id/photo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Apotik"
android:id="#+id/itemDescription"
android:layout_below="#+id/price"
android:layout_toEndOf="#+id/photo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/Qty"
android:layout_below="#+id/itemDescription"
android:layout_toEndOf="#+id/photo" />
<ImageButton
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/btnkurang"
android:layout_below="#+id/itemDescription"
android:layout_toEndOf="#+id/Qty"
android:src="#drawable/minus"/>
<ImageButton
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/btntambah"
android:layout_below="#+id/itemDescription"
android:layout_toEndOf="#+id/btnkurang"
android:src="#drawable/plus" />
</RelativeLayout>
Search view comes in the action bar. Therefore menu items need to be set up.
/*******************
* Menu Items
******************/
/*
Menu added to perform search on the action bar. Two menu items:
2. Open the search area on the action bar so that the user can search.
*/
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView sv = new SearchView(((MainActivity) getActivity()).getSupportActionBar().getThemedContext());
sv.setIconifiedByDefault(true);
sv.setFocusable(true);
sv.setIconified(false);
sv.clearFocus();
sv.requestFocusFromTouch();
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItemCompat.setActionView(item, sv);
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
sv.setIconifiedByDefault(true);
sv.setFocusable(true);
sv.setIconified(false);
sv.requestFocusFromTouch();
return false;
}
});
sv.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
item.collapseActionView();
hideKeyboard();
return true;
}
});
MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.action_search), new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
//DO SOMETHING WHEN THE SEARCHVIEW IS CLOSING
simpleSearch = null;
sv.setQuery(null, false);
hideKeyboard();
return true;
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
System.out.println("search query submit");
return false;
}
#Override
public boolean onQueryTextChange(String searchString) {
System.out.println(searchString);
classSearchArray.clear();
if (searchString.length() > 0) {
simpleSearch = searchString.toLowerCase();
for (ClassModel classObj : classArray) {
if (classObj.getName().toLowerCase().contains(simpleSearch) ||
classObj.getCity().toLowerCase().contains(simpleSearch) ||
classObj.getStaffName().toLowerCase().contains(simpleSearch) ||
classObj.getLocationName().toLowerCase().contains(simpleSearch)) {
classSearchArray.add(classObj);
}
}
ClassAdapter adapter = new ClassAdapter(classSearchArray, getActivity(), FindAClassFragment.this);
listViewSearch.setAdapter(adapter);
listView.setVisibility(View.GONE); //original list view
listViewSearch.setVisibility(View.VISIBLE); //search list view
} else {
simpleSearch = null;
listView.setVisibility(View.VISIBLE);
listViewSearch.setVisibility(View.GONE);
}
return false;
}
});
}
Menu XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search Items"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Try this way
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>
<!-- List View -->
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/product_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Listview Data
String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
"iPhone 4S", "Samsung Galaxy Note 800",
"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
Related
I created a listview with a custom adapter that allows me to have a list of items with checkboxes next to each item.
So I would like to look at the checkbox for the corresponding item in the list and see if it is checked and if it is, then set the value of boolean whiskey = false to true and so on for the other booleans.
It is very possible I have code in the wrong class or xml file, I've been trying to piece together things I've found on the internet. I'm new to android studio so its proving very difficult. I do have about a years worth of java experience though. I have all my code written in a working program on Eclipse, I am just having a hell of a time figuring out how to implement it into a working app.
Thanks in advance.
customAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends BaseAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public customAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
public void setChecked(boolean isChecked){
}
#Override
public View getView(final 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.activity2_listview, null);
}
//Handle TextView and display string from your list
TextView label = (TextView)view.findViewById(R.id.label);
label.setText(list.get(position));
//Handle buttons and add onClickListeners
CheckBox callchkbox = (CheckBox) view.findViewById(R.id.cb);
callchkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update isChecked value to model class of list at current position
list.get(position).setChecked(isChecked);
}
});
return view;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Main2Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import android.widget.CheckBox;
public class Main2Activity extends AppCompatActivity {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView listView = (ListView) findViewById(R.id.userIngredients);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(userIngredients));
listView.setAdapter(new customAdapter(list, Main2Activity.this));
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity"
android:id="#+id/linearLayout">
<ListView
android:layout_width="419dp"
android:layout_height="558dp"
android:id="#+id/userIngredients"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
tools:layout_conversion_absoluteHeight="731dp"
tools:layout_conversion_absoluteWidth="411dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="374dp"
android:layout_height="60dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Check Your Ingredients"
android:textSize="24sp"
app:fontFamily="#font/cinzel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
activity2_listview.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/label"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
i think you can do it with a BaseAdapter as well, but i suggest to use a RecyclerView instead.
I used support-v4 and recyclerview-v7 libs as following:
(Make sure that you are not developing AndroidX - check your gradle.properties of the entire project. It is very similar but uses other libraries though.)
build.gradle
android {
compileSdkVersion 28
buildToolsVersion '28.0.3'
...
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Your Ingredients"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_chooser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</android.support.v7.widget.RecyclerView>
</android.widget.RelativeLayout>
In the activity2_listview you might want to do more design to the xml. It looks very basic now.
activity2_listview.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="wrap_content">
<TextView
android:id="#+id/listviewtextlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/listviewcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the main class we implement a callback-listener for our custom onItemAction function. We pass the listener with adapter.setActionListener(this); and add the adapter to the RecyclerViewer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements CustomAdapter.ItemActionListener {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
CustomAdapter adapter;
RecyclerView.LayoutManager layoutManager;
RecyclerView recyclerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
recyclerListView = (RecyclerView) findViewById(R.id.recycler_chooser);
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(userIngredients));
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerListView.setHasFixedSize(false);
layoutManager = new LinearLayoutManager(this);
recyclerListView.setLayoutManager(layoutManager);
System.out.println("list.size() " + list.size());
adapter = new CustomAdapter(list,MainActivity.this);
adapter.setActionListener(this);
recyclerListView.setAdapter(adapter);
} catch (Exception e){
e.printStackTrace();
}
}
// callback listener for your items
#Override
public void onItemAction(View view, CustomAdapter.CustomActions customAction, int position) {
final String itemName = adapter.getItem(position);
System.out.println(customAction + ": You clicked " + itemName + " on row number " + position);
switch(itemName){
case "Whiskey":
if(customAction== CustomAdapter.CustomActions.CHECK){
Whiskey=true;
}
else{
Whiskey=false;
}
System.out.println("Whiskey set to: " + Whiskey);
break;
case "Bourbon":
if(customAction== CustomAdapter.CustomActions.CHECK){
Bourbon=true;
}
else{
Bourbon=false;
}
System.out.println("Bourbon set to: " + Bourbon);
break;
//case xyz
// and so on
default:
System.out.println("Not programmed yet: " + itemName);
}
}
}
As said above i removed the BaseAdapter and replaced it with the RecyclerView. We had to implement a custom ViewHolder-class that contains each row in our RecyclerViewList. Within the ViewHolder we can call the method on our listener whenever a checkbox-change event occurs.
CustomAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
//------ helper class for the viewholder
enum CustomActions{
CHECK,UNCHECK
}
// Provide a reference to the views for each row
public class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public CheckBox mCheckBox;
public CustomViewHolder(View v) {
super(v);
// the view element v is the whole linear layout element
CheckBox.OnCheckedChangeListener checkboxListenerForOneEntry = new CheckBox.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if (mItemActionListener != null) {
if(isChecked){
// this compoundbutton view element will be the checkbox
mItemActionListener.onItemAction(view, CustomActions.CHECK, getAdapterPosition());
}else{
mItemActionListener.onItemAction(view, CustomActions.UNCHECK, getAdapterPosition());
}
}
}
};
mTextView = v.findViewById(R.id.listviewtextlabel);
mCheckBox = v.findViewById(R.id.listviewcheckbox);
mCheckBox.setOnCheckedChangeListener(checkboxListenerForOneEntry);
}
}
//------
private ArrayList<String> list;
private Context context;
private LayoutInflater mInflater;
private ItemActionListener mItemActionListener;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
this.mInflater = LayoutInflater.from(this.context);
}
// allows clicks events to be caught
void setActionListener(ItemActionListener itemActionListener) {
this.mItemActionListener = itemActionListener;
}
// parent activity will implement this method to respond to click events
public interface ItemActionListener {
void onItemAction(View view, CustomActions customAction, int position);
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = mInflater.inflate(R.layout.activity2_listview, parent, false);
return new CustomViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(list.get(position));
}
#Override // Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return getCount();
}
public int getCount() {
return list.size();
}
public String getItem(int pos) {
return list.get(pos);
}
}
Feel free to use the code as you like.
For more info about the RecyclerView see the google docs: https://developer.android.com/guide/topics/ui/layout/recyclerview
So, I found this weird behavior listview that applying popup menu when a certain condition is met (on this case, if approval is "Unchecked" )
All item on the listview behave the way I expect, except the first item when value of approval is "Accept" or "Denied".
So, here is my code.
Order.java
package com.example.listview;
public class Order {
String name;
String approval;
public Order(String name, String approval) {
this.name = name;
this.approval = approval;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getApproval() {
return approval;
}
public void setApproval(String approval) {
this.approval = approval;
}
}
OrderAdapter.java
package com.example.listview;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class OrderAdapter extends BaseAdapter {
Activity activity;
List<Order> orders;
LayoutInflater inflater;
public OrderAdapter(Activity activity, List<Order> orders) {
this.activity = activity;
this.orders = orders;
inflater = activity.getLayoutInflater();
}
#Override
public int getCount() {
return orders.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if (view == null){
view = inflater.inflate(R.layout.lv_order_item, viewGroup, false);
holder = new ViewHolder();
holder.tvName = view.findViewById(R.id.tv_name);
holder.tvApproval = view.findViewById(R.id.tv_approval);
holder.rlPopUpMenu = view.findViewById(R.id.rl_popUpMenu);
view.setTag(holder);
}else
holder = (ViewHolder)view.getTag();
final Order model = orders.get(i);
holder.tvName.setText(model.getName());
holder.tvApproval.setText(model.getApproval());
holder.tvApproval.setTextColor(Color.parseColor("#D0CACA"));
// Condition For PopUp Menu
if(model.getApproval().equals("Unchecked")) {
// Menu Popup
holder.rlPopUpMenu.setVisibility(View.VISIBLE);
holder.rlPopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(view.getContext(), view);
popup.getMenuInflater().inflate(R.menu.order_item_popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(menuItem.getItemId() == R.id.action_accept) {
Toast.makeText(activity, "You Click Accept", Toast.LENGTH_SHORT).show();
}
if(menuItem.getItemId() == R.id.action_denied) {
Toast.makeText(activity, "You Click Denied", Toast.LENGTH_SHORT).show();
}
return true;
}
});
popup.show();
}
});
} else if(model.getApproval().equals("Accept")) {
holder.tvApproval.setTextColor(Color.parseColor("#32FF84"));
} else if(model.getApproval().equals("Denied")) {
holder.tvApproval.setTextColor(Color.parseColor("#1F9999"));
}
return view;
}
class ViewHolder{
TextView tvName;
TextView tvApproval;
RelativeLayout rlPopUpMenu;
}
}
OrderActivity.java
package com.example.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ScrollView;
import java.util.ArrayList;
import java.util.List;
public class OrderActivity extends AppCompatActivity {
List<Order> orders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
getSupportActionBar().setTitle("List View");
final ScrollView scrollView = findViewById(R.id.order_scrollview);
// To Scroll to the Top when Opening The Activity
scrollView.smoothScrollTo(0, 0);
final NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_order);
orders = new ArrayList<>();
orders.add(new Order("MikeA", "Accept"));
orders.add(new Order("MikeB", "Accept"));
orders.add(new Order("MikeC", "Unchecked"));
orders.add(new Order("MikeD", "Denied"));
orders.add(new Order("MikeE", "Unchecked"));
orders.add(new Order("MikeF", "Unchecked"));
orders.add(new Order("MikeG", "Unchecked"));
orders.add(new Order("MikeH", "Unchecked"));
orders.add(new Order("MikeI", "Accept"));
orders.add(new Order("MikeJ", "Unchecked"));
orders.add(new Order("MikeK", "Unchecked"));
orders.add(new Order("MikeL", "Unchecked"));
final OrderAdapter adapter = new OrderAdapter(this, orders);
non_scroll_list.setAdapter(adapter);
}
}
NonScrollListView.java
package com.example.listview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ListView;
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
Folder layout
activity_order.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/order_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:fillViewport="true"
android:background="#F2F2F2"
tools:context="com.example.listview.OrderActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F2F2F2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:background="#F2F2F2"
android:orientation="vertical">
<com.example.listview.NonScrollListView
android:id="#+id/lv_order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent"
android:background="#FFFFFF">
</com.example.listview.NonScrollListView>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
lv_order_item.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="wrap_content"
android:minHeight="80dp"
android:paddingBottom="13dp"
android:background="#991F1F">
<RelativeLayout
android:id="#+id/rl_popUpMenu"
android:layout_width="70dp"
android:layout_height="40dp"
android:gravity="center"
android:paddingLeft="30dp"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true">
<ImageView
android:layout_width="4dp"
android:layout_height="18dp"
android:src="#drawable/three_dots_order"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#fff"/>
<TextView
android:id="#+id/tv_approval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#fff"/>
</LinearLayout>
</RelativeLayout>
Folder menu
order_item_popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_accept"
android:title="Accept"/>
<item
android:id="#+id/action_denied"
android:title="Denied"/>
</menu>
And here is the picture of the list
As you can see, MikeA's approval value is "Accept",
so the popup menu (the three dot) should not appear.
So, is there anything that I miss ?
Replace your code with this
if(model.getApproval().equals("Unchecked")) {
// Menu Popup
holder.rlPopUpMenu.setVisibility(View.VISIBLE);
holder.rlPopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(view.getContext(), view);
popup.getMenuInflater().inflate(R.menu.order_item_popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(menuItem.getItemId() == R.id.action_accept) {
Toast.makeText(activity, "You Click Accept", Toast.LENGTH_SHORT).show();
}
if(menuItem.getItemId() == R.id.action_denied) {
Toast.makeText(activity, "You Click Denied", Toast.LENGTH_SHORT).show();
}
return true;
}
});
popup.show();
}
});
} else if(model.getApproval().equals("Accept")) {
holder.rlPopUpMenu.setVisibility(View.GONE);
holder.tvApproval.setTextColor(Color.parseColor("#32FF84"));
} else if(model.getApproval().equals("Denied")) {
holder.rlPopUpMenu.setVisibility(View.GONE);
holder.tvApproval.setTextColor(Color.parseColor("#1F9999"));
}
I am trying to create an app with a list of foods on the main activity and a checkbox for each food.
I followed this tutorial in order to do the whole text and checkbox thing: http://android-pratap.blogspot.co.il/2015/01/recyclerview-with-checkbox-example.html
But whenever I run the app it just won't show the RecyclerView on the main screen... (The app will run, but the RecyclerView just isn't there)
If someone can explain how I can change my code so it wouldn't require the cards that would be awesome. Here's my code:
MainAcitivity.java: (Just combines the RecyclerView with the FoodAdapter)
package com.gregskl.foodreminder;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private List<Food> foods;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
foods = new ArrayList<>();
foods.add(new Food("Grapes", true));
foods.add(new Food("Oranges", true));
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setLayoutManager(new LinearLayoutManager(this));
adapter = new FoodAdapater(foods);
recycler.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FoodAdapter.java:
package com.gregskl.foodreminder;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Gregory on 11-Sep-16.
*/
public class FoodAdapater extends RecyclerView.Adapter<FoodAdapater.ViewHolder> {
private List<Food> foods;
public FoodAdapater(List<Food> foods) {
this.foods = foods;
}
#Override
public FoodAdapater.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list, null);
return new ViewHolder(itemLayoutView);
}
#Override
public void onBindViewHolder(FoodAdapater.ViewHolder holder, int position) {
ViewHolder h = (ViewHolder) holder;
h.text.setText(foods.get(position).getText());
h.checkbox.setChecked(foods.get(position).isAvailable());
h.checkbox.setTag(foods.get(position));
h.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(v.getContext(), "Hey", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return foods.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public CheckBox checkbox;
public ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
}
}
}
Food.java: (The data model for the food)
package com.gregskl.foodreminder;
/**
* Created by Gregory on 11-Sep-16.
*/
public class Food {
private String text;
private boolean available;
public Food(String text, boolean available) {
this.text = text;
this.available = available;
}
public String getText() {
return text;
}
public boolean isAvailable() {
return available;
}
public void setText(String text) {
this.text = text;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gregskl.foodreminder.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:scrollbars="vertical" />
</RelativeLayout>
list.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Try setting height from android:layout_height="0dp" to android:layout_height="match_parent" in your RecyclerView.
0dp height is used in LinearLayout, yours is RelativeLayout.
I am fairly new to Java and Android development. I am currently creating a shopping app and was looking at adding a "Remove" button to my Shopping Cart list.
Here is my current code for my list activity for my shopping cart, I am not really sure where to begin and some guidance would be greatly appreciated.
Thanks
package .shopper;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class CartListActivity extends ListActivity {
public class ProductListAdapter extends BaseAdapter {
private final Context context;
private List<Product> itemList;
public List<Product> getItemList() {
return itemList;
}
public void setItemList(List<Product> itemList) {
this.itemList = itemList;
}
public Context getContext() {
return context;
}
public ProductListAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
if(itemList == null) return 0;
else return itemList.size();
}
#Override
public Object getItem(int position) {
if (itemList == null) return null;
else return itemList.get(position);
}
#Override
public long getItemId(int position) {
if (itemList == null) return 0;
else return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_product_list, parent, false);
}
Product p = itemList.get(position);
//set value into textview according to position
TextView textView = (TextView) cell.findViewById(R.id.product_title);
textView.setText(p.getProductName());
// add £ symbol
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price: " + "£"+ p.getPrice());
//set value into imageview according to position
ImageView imgView = (ImageView) cell.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
//and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
}
public static final Integer[] productIcons = {
0, // index 0 is empty
R.drawable.books,
R.drawable.films,
R.drawable.music,
R.drawable.games,
};
private int categoryId;
private ProductListAdapter adapter;
private ListViewLoader loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the category from the intent
Intent intent = getIntent();
categoryId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
adapter = new ProductListAdapter(this);
setListAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
loader = new ListViewLoader(adapter, categoryId);
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_cart:
//create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//create an intent
Intent intent = new Intent(this, ProductActivity.class);
Product p = (Product)adapter.getItem(position);
//specify the extra parameters we want to pass
intent.putExtra(MainActivity.SELECTED_CATEGORY, p.getCategoryId());
intent.putExtra(MainActivity.SELECTED_PRODUCTID, p.getProductId());
intent.putExtra(MainActivity.SELECTED_PRODUCTNAME, p.getProductName());
intent.putExtra(MainActivity.SELECTED_PRODUCTPRICE, p.getPrice());
intent.putExtra(MainActivity.SELECTED_SUITABLEFORKIDS, p.getSuitableForKids());
startActivity(intent);
}
}
EDIT:
XML for adapter_product_list
<?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:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
</RelativeLayout>
Change your xml like following
<?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:padding="8dp" >
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentLeft="true"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/product_image"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_title"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Delete" />
</RelativeLayout>
And in your adapter inside getView() function add this
Button deleteBtn = (Button) findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
itemList.remove(position);
notifyDataSetChanged();
}
});
1) hope p.loadImage(imgView, 54, 54); is running in a asyncTask
2) if you want to click on a button in a row of a ListView than you shoudl add the button to your row layout and implent onClickListenr of that button in your getView method of adapter.in onClick method yous hould have:
if(position<itemList.size()){
//TO REMOVE TEM FROM ARRAY LIST
itemList.remove(position);
//TO Update the ListView
notifyDataSetChanged();
}
you can implement a multy line delete,by adding a checkbox in your listRow and adding the positon of the item to be deleted to an arrayList of Integers and after click-ing the delete button you should delete all the items from the imteList and after that call notifyDataSetChanged()
EDIT
<?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:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/deleteBtn"
android:layout_width="wrap_content
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_info"
</RelativeLayout>
you should add this button to your layout, and in getView method of adapter add
Button delete=v.findViewById(R.id.deleteBtn);
delete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//THE PART I WROTE ABOVE
}
})
I am trying to add a checkbox in a customized listview but don't know how.
I have the following codes:
ListObject.java
package br.com.eduvm.xurrascalc;
public class ListObject {
private String texto;
private int iconeRid;
public ListObject() {
}
public ListObject(String texto, int iconeRid) {
this.texto = texto;
this.iconeRid = iconeRid;
}
public int getIconeRid() {
return iconeRid;
}
public void setIconeRid(int iconeRid) {
this.iconeRid = iconeRid;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
}
ListAdapter.java
package br.com.eduvm.xurrascalc;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<ListObject> itens;
public ListAdapter(Context context, ArrayList<ListObject> itens) {
// Itens que preencheram o listview
this.itens = itens;
// responsavel por pegar o Layout do item.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return itens.size();
}
public ListObject getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ListObject item = itens.get(position);
view = mInflater.inflate(R.layout.itens_lista, null);
((TextView) view.findViewById(R.id.text)).setText(item.getTexto());
((ImageView) view.findViewById(R.id.imagemview)).setImageResource(item.getIconeRid());
return view;
}
}
List.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5sp" >
<ImageView
android:id="#+id/imagemview"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5sp"
android:gravity="center_vertical"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
How could I do to insert a checkbox in the items in this list?
This would be the layout for each individual row in your list
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/lstChkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lstText"
android:textSize="30px"
android:layout_weight="1" />
<ImageView
android:id="#+id/listImage"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
You main list activity layout will look something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:choiceMode="multipleChoice"
/>
Your class which extends BaseAdapter getView method will somethings like this:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vHolder = null;
if (convertView != null)
vHolder = (ViewHolder) convertView.getTag(); // convertView is been recycled
else {
convertView = (View) mInflater.inflate(R.layout.list_item, null); // Set content of new View with list_item.xml
vHolder = new ViewHolder();
vHolder.checkBox = ((CheckBox) convertView.findViewById(R.id.lstChkbox)); // Getting pointers
vHolder.textView = ((TextView) convertView.findViewById(R.id.lstText));
vHolder.imageView = ((ImageView) convertView.findViewById(R.id.listImage));
vHolder.checkBox.setOnCheckedChangeListener(this); // Setting Listeners
convertView.setTag(vHolder);
}
vHolder.checkBox.setId(position); // This is part of the Adapter APi
vHolder.textView.setId(position); // Do not delete !!!
vHolder.imageView.setId(position);
if (mItems.get(position).getChecked()) { // Setting parameters for the View from our mItems list
vHolder.checkBox.setChecked(true);
} else {
vHolder.checkBox.setChecked(false);
}
vHolder.textView.setText(mItems.get(position).getText());
vHolder.imageView.setImageDrawable(mItems.get(position).getmImage());
return convertView;
}
public static class ViewHolder {
CheckBox checkBox;
TextView textView;
ImageView imageView;
}
/*
* Ok for this test but Toast are going to show every time the row comes into View
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "Checked");
int position = buttonView.getId();
if (isChecked) {
mItems.get(position).setChecked(true);
Toast.makeText(context, mItems.get(position).getText(), Toast.LENGTH_LONG).show();
} else {
mItems.get(buttonView.getId()).setChecked(false);
}
}
Just add a checkbox to the layout itens_lista.xml.
Just adding a checkbox is easy. Do you want to do anything more to ti.
Add a CheckBox View to your custom row layout.