I have requirement to create nested recyclerView like
RecyclerView Contains-> CardView contains-> RecyclerView.
If I click on card I'm getting child position only but I also need parent card position. How can I handle click events of both Recyclerview and CardView at same time?
MainActivity.java:
public class MainActivity extends Activity {
LinearLayout linView;
private RecyclerView main_view;
RootAdapter adapter2;
private RelativeLayout mRelativeLayout;
private Context mContext;
private Activity mActivity;
int pos = 0;
int main_pos;
private static RecyclerView.Adapter adapter;
private static RecyclerView.Adapter adapterCo;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<DataModelMain> dataMain;
private static ArrayList<DataModel_CO> dataCo;
static View.OnClickListener myOnClickListener;
static View.OnClickListener onClickListener;
private static ArrayList<Integer> removedItems;
TestMain mainData = new TestMain();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prof = (ImageView) findViewById(R.id.profile);
main_view = (RecyclerView) findViewById(R.id.recycler_main);
mRelativeLayout = (RelativeLayout) findViewById(R.id.partners);
cont = (TextView) findViewById(R.id.mobile);
iconType = (ImageView) findViewById(R.id.icon_type);
linView = (LinearLayout) findViewById(R.id.layout_view);
// Get the application context
mContext = getApplicationContext();
// Get the activity
mActivity = MainActivity.this;
myOnClickListener = new MyOnClickListener(this);
onClickListener = new OnClickListener(this);
main_view.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(
this,
LinearLayoutManager.VERTICAL,
false
) {
};
main_view.setLayoutManager(layoutManager);
main_view.setItemAnimator(new DefaultItemAnimator());
dataMain = new ArrayList<DataModelMain>();
getMainData();
setMainView();
}
}
private void getMainData() {
for (int i = 0; i < mainData.passengers.length; i++) {
dataMain.add(new DataModelMain(
mainData.type[i],
mainData.passengers[i],
mainData.p_name[i],
mainData.p_contact[i],
mainData.p_flight[i],
mainData.p_pnr[i],
mainData.air[i],
mainData.p_time[i]
));
}
adapter2 = new RootAdapter(this, dataMain);
main_view.setAdapter(adapter2);
}
private class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
setMainView();
}
}
private class OnClickListener implements View.OnClickListener {
private final Context context1;
private OnClickListener(Context context0) {
this.context1 = context0;
}
#Override
public void onClick(View v) {
showIcons(v);
}
private void showIcons(View v) {
pos = main_view.getChildPosition(v);
Log.e("CLICKED","pos: "+pos);
}
}
private class RootAdapter extends RecyclerView.Adapter<RootAdapter.RootViewHolder> {
private final LayoutInflater inflater;
String[] _items = new String[]{"GROUP 1", "GROUP 2", "GROUP 3", "GROUP 4"};
private ArrayList<DataModelMain> dataSet;
public RootAdapter(Context context,ArrayList<DataModelMain> data) {
inflater = LayoutInflater.from(context);
this.dataSet = data;
}
#Override
public RootViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = inflater.inflate(R.layout.card_main, viewGroup, false);
RootViewHolder rvi = new RootViewHolder(view);
view.setOnClickListener(MainActivity.onClickListener);
return rvi;
}
#Override
public void onBindViewHolder(RootViewHolder rootViewHolder, int i) {
rootViewHolder.recyclerViewChild.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
rootViewHolder.recyclerViewChild.setAdapter(new ChildAdapter(inflater,dataSet));
}
#Override
public int getItemCount() {
return _items.length;
}
class RootViewHolder extends RecyclerView.ViewHolder {
RecyclerView recyclerViewChild;
public RootViewHolder(View itemView) {
super(itemView);
recyclerViewChild = (RecyclerView) itemView.findViewById(R.id.recycler_partners);
}
}
}
private class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
private LayoutInflater _inflater;
private ArrayList<DataModelMain> dataSet;
public ChildAdapter(LayoutInflater inflater,ArrayList<DataModelMain> data) {
_inflater = inflater;
this.dataSet = data;
}
#Override
public ChildViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = _inflater.inflate(R.layout.card_partner, viewGroup, false);
ChildViewHolder rvi = new ChildViewHolder(view);
view.setOnClickListener(MainActivity.myOnClickListener);
return rvi;
}
#Override
public void onBindViewHolder(ChildViewHolder holder, int listPosition) {
TextView name = holder.tvName;
TextView cont = holder.tvCont;
TextView flight = holder.tvFlight;
TextView pnr = holder.tvPNR;
TextView time = holder.tvTime;
ImageView type = holder.im_type;
ImageView pic = holder.im_pic;
ImageView logo = holder.im_logo;
CardView cardView = holder.card;
name.setText(dataSet.get(listPosition).getName());
cont.setText(dataSet.get(listPosition).getContact());
flight.setText(dataSet.get(listPosition).getFlight());
pnr.setText(dataSet.get(listPosition).getPnr());
time.setText(dataSet.get(listPosition).getTime());
type.setImageResource(dataSet.get(listPosition).getType());
pic.setImageResource(dataSet.get(listPosition).getImage());
logo.setImageResource(dataSet.get(listPosition).getLogo());
switch (dataSet.get(listPosition).getType()){
case R.mipmap.gov:
cardView.setCardBackgroundColor(Color.parseColor("#FAFAD2"));
break;
case R.mipmap.vip:
cardView.setCardBackgroundColor(Color.parseColor("#CDFFCD"));
break;
case R.mipmap.jail:
cardView.setCardBackgroundColor(Color.parseColor("#FFE4E1"));
break;
case R.mipmap.ban:
cardView.setCardBackgroundColor(Color.parseColor("#DCDCDC"));
break;
}
}
#Override
public int getItemCount() {
return dataSet.size();
}
public class ChildViewHolder extends RecyclerView.ViewHolder {
ImageView im_type,im_pic,im_logo;
TextView tvName,tvCont,tvFlight,tvPNR,tvTime;
CardView card;
public ChildViewHolder(View itemView) {
super(itemView);
this.card = (CardView) itemView.findViewById(R.id.card_view);
this.im_type = (ImageView) itemView.findViewById(R.id.p_type);
this.im_pic = (ImageView) itemView.findViewById(R.id.p_profile);
this.im_logo = (ImageView) itemView.findViewById(R.id.p_air_lines);
this.tvName = (TextView) itemView.findViewById(R.id.p_name);
this.tvCont = (TextView) itemView.findViewById(R.id.p_mob);
this.tvFlight = (TextView) itemView.findViewById(R.id.p_flight);
this.tvPNR = (TextView) itemView.findViewById(R.id.p_pnr);
this.tvTime = (TextView) itemView.findViewById(R.id.p_timer);
}
}
}
}
How about making the root/parent cardView clickable??
Give an id to the cardView item of the parent recyclerView. Place it in your ViewHolderClass and then assign a onCLickListener to the cardView in BindViewHolder like this:
rootViewHolder.rootCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// keep an track of the selected position of the cardView and store it in a global/local variable
}
});
you can track the adapter position of the selected cardView using
rootViewHolder.getAdapterPosition()
Note: rootViewHolder is written as per your ViewHolder class
I hope this helps !!
Related
So I have an activity with a listview inside of it and when I click a delete button I want to remove the object from the list. I already know how to find which object I want to remove and remove it from the list that populates my array adapter but I am not sure what i need to do to call the .notifyDataSetChanged() routine which Is what I believe I need to do. Any help would be much appreciated.
My activity code
public class MealActivity2 extends AppCompatActivity {
private ListView lv;
public static ArrayList<Model> modelArrayList;
private CustomAdapter customAdapter;
private Button btnnext;
private String[] fruitlist = new String[]{"Apples", "Oranges", "Potatoes", "Tomatoes","Grapes"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
Integer numFoodItems = ((Globals) getApplication()).getLength();
lv = (ListView) findViewById(R.id.lv);
btnnext = (Button) findViewById(R.id.next);
modelArrayList = getModel(numFoodItems);
customAdapter = new CustomAdapter(this);
lv.setAdapter(customAdapter);
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MealActivity2.this,NextActivity.class);
startActivity(intent);
}
});
}
// this builds the array list of model opbjects that will be used by the adapter to populate
// the list view dynamically
private ArrayList<Model> getModel(Integer length){
ArrayList<Model> list = new ArrayList<>();
for(int i = 0; i < length; i++){
FoodDetailsPost food = ((Globals) getApplication()).getFoodList().get(i);
Model model = new Model();
model.setNumber(((Globals) getApplication()).getServing(i));
model.setFruit(food.getDescription());
list.add(model);
}
return list;
}
}
and here is my custom adapter code if you look near the end at the last comment that is where i need to notify my activity that I have changed the contents of the list and should update the displaying items
public class CustomAdapter extends BaseAdapter {
private Context context;
private adapterGlobalAccess g = new adapterGlobalAccess();
private CustomAdapter customAdapter;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return MealActivity2.modelArrayList.size();
}
#Override
public Object getItem(int position) {
return MealActivity2.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.tvFruit = (TextView) convertView.findViewById(R.id.animal);
holder.tvnumber = (TextView) convertView.findViewById(R.id.number);
holder.btn_edit = (Button) convertView.findViewById(R.id.plus);
holder.btn_minus = (Button) convertView.findViewById(R.id.minus);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.tvFruit.setText(MealActivity2.modelArrayList.get(position).getFruit());
holder.tvnumber.setText(String.valueOf(MealActivity2.modelArrayList.get(position).getNumber()));
holder.btn_edit.setTag(R.integer.btn_plus_view, convertView);
holder.btn_edit.setTag(R.integer.btn_plus_pos, position);
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_edit.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_edit.getTag(R.integer.btn_plus_pos);
Double number = Double.parseDouble(tv.getText().toString()) + 1;
tv.setText(String.valueOf(number));
MealActivity2.modelArrayList.get(pos).setNumber(number);
g.setServing(pos, number);
}
});
holder.btn_minus.setTag(R.integer.btn_minus_view, convertView);
holder.btn_minus.setTag(R.integer.btn_minus_pos, position);
holder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_minus.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_minus.getTag(R.integer.btn_minus_pos);
((Globals) context.getApplicationContext()).remove(pos);
MealActivity2.modelArrayList.remove(pos);
// i need to do .notifyDataSetChanged() here but im not sure how
}
});
return convertView;
}
You can just use a interface to solve the problem
CustomAdapter
public class CustomAdapter extends BaseAdapter {
...
private CustomAdapterListener listener;
interface CustomAdapterListener{
void itemClick();
}
public CustomAdapter(Context context, CustomAdapterListener listener) {
this.context = context;
this.listener = listener;
}
MainActivity2
public class MealActivity2 extends AppCompatActivity implements CustomAdapterListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
...
customAdapter = new CustomAdapter(this, this);
}
#Override
public void itemClick() {
// you can do .notifyDataSetChanged() here
}
after that you can use listener to callback to Activity and do anything you want
CustomAdapter
#Override
public void onClick(View v) {
listener.itemClick();
// i need to do .notifyDataSetChanged() here but im not sure how
}
[Code below] Item in RecycleView doesn't click [it should open the DetailActivity], I try to find the mistake but I didn't understand where
What I try :
Change size items
Change RecycleView to VERTICAL
Write Log.v
I have the same RecycleViewAdapter but it vertical, and it is working well.
my all project : https://github.com/sanke46/E-Commerce
RecycleViewAdapter :
public class SalesRecyclerViewAdapter extends RecyclerView.Adapter<SalesRecyclerViewAdapter.ViewHolder> {
BasketActivity basketActivity = new BasketActivity();
private List<Item> itemList = basketActivity.getBasketItem();
private ArrayList arr;
private Context mContext;
public SalesRecyclerViewAdapter(Context context, ArrayList<Item> data) {
this.arr = data;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sale, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Item item = (Item) arr.get(position);
Picasso.with(mContext).load(item.getImageUrl()).into(holder.imageView);
holder.price.setText(item.getPrice() + " $");
holder.price.setPaintFlags(holder.price.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
holder.fixPrice.setText(item.getDiscontPrice() + " $");
holder.name.setText(item.getName());
holder.comment.setText(item.getComment());
holder.gramm.setText(item.converGramms(String.valueOf(item.getGramms())));
holder.kal.setText(item.getKalories() + " kal");
holder.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemList.add((Item) arr.get(position));
basketActivity.setBasketItem(itemList);
}
});
holder.linerSaleClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra("item", item);
mContext.startActivity(intent);
Log.v("SALES", "SALES");
}
});
}
#Override
public int getItemCount() {
return arr.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout linerSaleClick;
private ImageView imageView;
private TextView price;
private TextView fixPrice;
private TextView name;
private TextView comment;
private TextView gramm;
private TextView kal;
private Button addToCart;
public ViewHolder(View itemView) {
super(itemView);
linerSaleClick = itemView.findViewById(R.id.linerSaleClick);
imageView = itemView.findViewById(R.id.imageSale);
price = itemView.findViewById(R.id.price);
kal = itemView.findViewById(R.id.kal);
gramm = itemView.findViewById(R.id.gramm);
name = itemView.findViewById(R.id.name);
comment = itemView.findViewById(R.id.comments);
fixPrice = itemView.findViewById(R.id.fixPrice);
addToCart = itemView.findViewById(R.id.buttonTwo);
}
}}
Basically code on your github is different than what you posted. So probably the reason of problem is:
In list_sale.xml
I noticed that in this view com.makeramen.roundedimageview.RoundedImageView you set parametr android:clickable="true" then if you want to rise click event on parent (RelativeLayout) it will not work. Solution: remove this line android:clickable="true".
I want to display number of total items of my recyclerview in a textview. If new item is added or deleted that textview should be update. And also calculate total price of items in a list of Items in a recyclerview and display in a textview below recyclerview list.
Below is my recyclerview adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.into(holder.imgProduct);
// holder.tvProductStatus.setText(productModelList.get(position).getIsAvailable());
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
//holder.tvMaterial.setText(productModelList.get(position).getMaterial());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity,tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView)itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and java Class:
public class CartActivity extends AppCompatActivity {
DatabaseHandler helper;
List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
TextView tvTotalNoOfItems, tvTotalPrice;
String p;
String i;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
p = getIntent().getStringExtra("variant_id");
i = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
p = extras.getString("variant_id");
i= extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList= new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new CartAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
tvTotalNoOfItems = (TextView)findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView)findViewById(R.id.tvTotalCartItemsPrice);
String totalPrice = "";
for (int i = 0; i<dbList.size(); i++)
{
totalPrice = totalPrice + dbList.get(i).getPrice().toString();
}
tvTotalPrice.setText(totalPrice);
btnContinueShopping = (Button)findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCOllectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCOllectionActivity);
finish();
}
});
btnCheckout = (Button)findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCheckoutActivity = new Intent(CartActivity.this,CheckoutActivity.class);
startActivity(launchCheckoutActivity);
}
});
}
}
First, add following getter to your adapter:
public List<ProductModel> getItems(){
return productModelList;
}
Then, you can subscribe on adapter data change and do the following:
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged () {
tvTotalNoOfItems.setText(mAdapter.getItemCount());
String totalPrice = "";
for (int i = 0; i < ((CartAdapter)mAdapter).getItems().size(); i++) {
totalPrice = totalPrice + ((CartAdapter)mAdapter).getItems().get(i).getPrice().toString();
}
tvTotalPrice.setText("" + totalPrice);
}
});
just add this line below the adapter set line
tvTotalNoOfItems.setText(mAdapter.getCount());
and add this into you adapter class where you delete action perform
String totalPrice = "";
((CartActivity)context).tvTotalNoOfItems.setText(getCount());
for (int i = 0; i<productModelList.size(); i++)
{
totalPrice = totalPrice + productModelList.get(i).getPrice().toString();
}
((CartActivity)context).tvTotalPrice.setText(""+totalPrice);
Just public you textview like this
public TextView tvTotalNoOfItems, tvTotalPrice;
I am trying to implement RecyclerView and CardView and I am working with json.
All my code is working fine and RecyclerView adapter is also not showing any error.
But in my main activity when i try to call adapter it is showing a error.
I took all the reference from here
Foodlist.java
public class FoodList extends RecyclerView.Adapter<FoodList.FoodViewHolder>{
private final Activity context;
LayoutInflater inflater;
public static class FoodViewHolder extends RecyclerView.ViewHolder {
TextView txt1;
TextView txt2;
TextView txt3;
TextView txt4;
CardView cv;
FoodViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
txt1 = (TextView) itemView.findViewById(R.id.txt1);
txt2 = (TextView) itemView.findViewById(R.id.txt2);
txt3 = (TextView) itemView.findViewById(R.id.txt3);
txt4 = (TextView) itemView.findViewById(R.id.txt4);
}
}
List<Food> food;
public FoodList(Activity context, List<Food> food) {
this.food = food;
inflater = context.getLayoutInflater();
this.context = context;
}
#Override
public FoodViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.examplelistview, viewGroup, false);
FoodViewHolder fvh = new FoodViewHolder(v);
return fvh;
}
#Override
public void onBindViewHolder(FoodViewHolder holder, int position) {
View view;
view = inflater.inflate(R.layout.examplelistview, null, true);
if (view == null) {
holder.txt1 = (TextView)view.findViewById(R.id.txt1);
holder.txt2 = (TextView) view.findViewById(R.id.txt2);
holder.txt3 = (TextView) view.findViewById(R.id.txt3);
holder.txt4 = (TextView) view.findViewById(R.id.txt4);
view.setTag(holder);
}
else {
holder = (FoodViewHolder) view.getTag();
}
final Food item = food.get(position);
holder.txt1.setText(item.txt1);
holder.txt2.setText(item.txt2);
holder.txt3.setText(item.txt3);
holder.txt4.setText(item.txt4);
}
#Override
public int getItemCount() {
return food.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Food.java:
public class Food {
public String txt1, txt2, txt3, txt4;
}
FoodViewHolder.java
public class FoodViewHolder {
TextView txt1, txt2, txt3, txt4;
}
MainActivity.java
RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(llm);
final FoodList adapter = new FoodList(MainActivity.this,food);
rv.setAdapter(adapter);
And I want to call my adapter in json below in another function:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setAdapter(adapter<here it is showing the error>, new DialogInterface.OnClickListener() {
}
What should i do?
Thanks in Advance
I implemented an setOnClickListener in my getView method to add the a product to my ArrayList, but my class doesn't recognize the method itemClicked, when i call the OnClick method inside the getView.
Adapter:
public class GridAdapter extends BaseAdapter{
private Context ctx;
private ArrayList<Produto> list ;
GridAdapter(Context context, ArrayList<Produto> s){
this.ctx = context;
this.list = s;
}
#Override
public View getView(int position, View convertiew, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertiew == null){
grid = new View(ctx);
grid = inflater.inflate(R.layout.grid_row, null);
TextView textView = (TextView) grid.findViewById(R.id.tv_gridrow);
ImageView imageView = (ImageView)grid.findViewById(R.id.img_gridrow);
textView.setText(list.get(position).getNome());
imageView.setImageResource(list.get(position).getImagem());
imageView.setAdjustViewBounds(true);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ctx.itemClicked(position);
}
});
} else {
grid = (View) convertiew;
}
return grid;
}
MainActivity
public class MainActivity extends Activity {
private ArrayList<Produto> array_produtos;
private ArrayList<Pedido> produtos_pedidos;
private int numero_pedidos;
private Produto produto_1;
private Produto produto_2;
private Produto produto_3;
private Produto produto_4;
private Produto produto_5;
private Pedido pedido_1;
private TextView apresenta_total;
private GridView gv;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
array_produtos = new ArrayList<Produto>();
produtos_pedidos = new ArrayList<Pedido>();
numero_pedidos=0;
//Inicialização dos produtos
produto_1 = new Produto(1, "Café",0.60,4,4,R.drawable.cafe1);
produto_2 = new Produto(2, "Água", 0.90,3,2, R.drawable.luso1);
produto_3 = new Produto(3, "Sopa", 1.20,2,5, R.drawable.sopa3);
produto_4 = new Produto(4, "Cerveja", 1.00,5,4, R.drawable.fino2);
produto_5 = new Produto(5, "Coca-cola", 1.10, 3,2, R.drawable.coca_cola1);
array_produtos.add(produto_1);
array_produtos.add(produto_2);
array_produtos.add(produto_3);
array_produtos.add(produto_4);
array_produtos.add(produto_5);
pedido_1 = new Pedido(); //cria primeiro pedido
produtos_pedidos.add(pedido_1); //Atribui à lista de pedidos
gv = (GridView)findViewById(R.id.gv_produtos);
lv = (ListView) findViewById(R.id.lv_produtos_pedidos);
gv.setAdapter(new GridAdapter(this, array_produtos));
ArrayAdapter<Pedido> arrayAdapter = new ArrayAdapter<Pedido>(this, android.R.layout.simple_list_item_1,produtos_pedidos);
lv.setAdapter(arrayAdapter);
}
public void itemClicked(int position) {
produtos_pedidos.get(0).addProduto(produto_1);
}
Have you try to cast your context?
#Override
public void onClick(View v) {
if(ctx instanceof MyActivity){
((MyActivity)ctx).itemClicked(int position);
}
Cheers