I can't find a tutorial to help me create a menu in Wearable RecyclerView. Everything that pops up up is related to Recyclerview for mobile phones. So I'm asking does the Wearable version work in the same manner or not?
I followed what was in the documentation but I don't know how to add items so that I would end up with something like this:
Edit:
So after messing around a bit and seeing the code for the Recyclerview here:https://codinginflow.com/tutorials/android/simple-recyclerview-java/part-2-adapter (Very helpful by the way)
I managed to create a list of items. Problem is they're lined up vertically with large spaces between them. I have placed the lines of code in the documentation that were supposed to line them up like in the image but I don't know what the problem is.
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.wear.ambient.AmbientModeSupport;
import androidx.wear.widget.WearableLinearLayoutManager;
import androidx.wear.widget.WearableRecyclerView;
import java.util.ArrayList;
import java.util.List;
public class circular_menu_external extends FragmentActivity
implements AmbientModeSupport.AmbientCallbackProvider, MenuItem.OnMenuItemClickListener {
// Fragment toolsfragment = new Tools();
// Fragment modesfragment = new Modes();
// Fragment keysfragment = new Keys();
// Fragment flowratefragment = new Flowrates();
private WearableRecyclerView wearableRecyclerView;
private Button btn;
private ArrayList<ExampleItem> mExampleList;
private RecyclerView.Adapter mAdapter;
private WearableRecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circular_menu_external);
wearableRecyclerView = findViewById(R.id.main_recycler_view);
mAdapter = new MenuRecyclerViewAdapter(mExampleList);
//Create a curved layout
CustomScrollingLayoutCallback customScrollingLayoutCallback = new CustomScrollingLayoutCallback();
// WearableLinearLayoutManager wearableLinearLayoutManager = new WearableLinearLayoutManager(this);
// wearableRecyclerView.setLayoutManager(wearableLinearLayoutManager);
// CustomScrollingLayoutCallback customScrollingLayoutCallback = new CustomScrollingLayoutCallback();
wearableRecyclerView.setLayoutManager(
new WearableLinearLayoutManager(this, customScrollingLayoutCallback));
// wearableRecyclerView.setLayoutManager(new WearableLinearLayoutManager(this));
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
createExampleList();
buildRecyclerView();
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
}
private void action_1() {
Intent i1 = new Intent(circular_menu_external.this, Settings.class);
startActivity(i1);
}
private void action_2(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode1.class);
startActivity(i1);
}
private void action_3(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode2.class);
startActivity(i1);
}
private void action_4(){
Intent i1 = new Intent(circular_menu_external.this, tool1mode3.class);
startActivity(i1);
}
private void cancelMenu(){
Intent i1 = new Intent(circular_menu_external.this, Main_menu.class);
startActivity(i1);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
#Override
public AmbientModeSupport.AmbientCallback getAmbientCallback() {
return null;
}
public void createExampleList() {
mExampleList = new ArrayList<>();
mExampleList.add(new ExampleItem(R.drawable.tool_ic, "Line 1", "Line 2"));
mExampleList.add(new ExampleItem(R.drawable.mode_ic, "Line 3", "Line 4"));
mExampleList.add(new ExampleItem(R.drawable.key, "Line 5", "Line 6"));
mExampleList.add(new ExampleItem(R.drawable.flow_ic, "Line 7", "Line 8"));
}
public void buildRecyclerView() {
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
wearableRecyclerView.setHasFixedSize(true);
wearableRecyclerView.setEdgeItemsCenteringEnabled(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MenuRecyclerViewAdapter(mExampleList);
wearableRecyclerView.setLayoutManager(mLayoutManager);
wearableRecyclerView.setAdapter(mAdapter);
//Add a circular scrolling gesture
wearableRecyclerView.setCircularScrollingGestureEnabled(true);
wearableRecyclerView.setBezelFraction(0.5f);
wearableRecyclerView.setScrollDegreesPerScreen(90);
}
public class CustomScrollingLayoutCallback extends WearableLinearLayoutManager.LayoutCallback {
/** How much should we scale the icon at most. */
private static final float MAX_ICON_PROGRESS = 0.65f;
private float progressToCenter;
#Override
public void onLayoutFinished(View child, RecyclerView parent) {
// Figure out % progress from top to bottom
float centerOffset = ((float) child.getHeight() / 2.0f) / (float) parent.getHeight();
float yRelativeToCenterOffset = (child.getY() / parent.getHeight()) + centerOffset;
// Normalize for center
progressToCenter = Math.abs(0.5f - yRelativeToCenterOffset);
// Adjust to the maximum scale
progressToCenter = Math.min(progressToCenter, MAX_ICON_PROGRESS);
child.setScaleX(1 - progressToCenter);
child.setScaleY(1 - progressToCenter);
}
}
}
This is the adapter:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.wear.widget.WearableRecyclerView;
import java.util.ArrayList;
public class MenuRecyclerViewAdapter extends WearableRecyclerView.Adapter<MenuRecyclerViewAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends WearableRecyclerView.ViewHolder {
public ImageView mImageView1,mImageView2,mImageView3,mImageView4;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView1 = itemView.findViewById(R.id.imageView1);
mImageView2 = itemView.findViewById(R.id.imageView2);
mImageView3 = itemView.findViewById(R.id.imageView3);
mImageView4 = itemView.findViewById(R.id.imageView4);
}
}
public MenuRecyclerViewAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView1.setImageResource(currentItem.getImageResource());
holder.mImageView2.setImageResource(currentItem.getImageResource());
holder.mImageView3.setImageResource(currentItem.getImageResource());
holder.mImageView4.setImageResource(currentItem.getImageResource());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
the xml file for my items:
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.CircularProgressLayout
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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageButton
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/homeicon4"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/bypass3"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/dualflow3"
tools:ignore="MissingConstraints" />
<ImageButton
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/round_shape"
android:src="#drawable/isolation3"
tools:ignore="MissingConstraints" />
</RelativeLayout>
</androidx.wear.widget.CircularProgressLayout>
Related
I am creating a ecommerce application. In which I am managing Cart screen.
The cart screen is included in HomeFragment's layout. From the adapter I am calling interface to transfer the data and update to the cart screen which appears when the cart value is greater than -> 0.
The problem is that when I click on "Add to cart" button of any item from recyclerview the "Add to cart" disappers and counter layout appears. as shown in the below images.
Clicking on single item ther other rows's "Add to cart" button disappears which must be not disapper. It is affecting multiple rows on single row change.
How to solve that issue any solution from your side?
HomeFragment.java
package com.example.rangeela_cart.Fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.rangeela_cart.Activity.CartActivity;
import com.example.rangeela_cart.Adapter.HomeFragImageSliderAdapter;
import com.example.rangeela_cart.Adapter.HomeFragLatestProAdapter;
import com.example.rangeela_cart.Adapter.HomeFragPopularProAdapter;
import com.example.rangeela_cart.R;
import com.example.rangeela_cart.databinding.ActivityCartBinding;
import com.example.rangeela_cart.databinding.FragmentHomeBinding;
import com.example.rangeela_cart.models.HomeFragImageSliderModel;
import com.example.rangeela_cart.models.HomeFragLatestProModel;
import com.example.rangeela_cart.models.HomePopularProModel;
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
private View view;
public FragmentHomeBinding binding;
private List<HomeFragImageSliderModel> imageSliderModelList = new ArrayList<>();
private HomeFragImageSliderAdapter adapter;
private List<HomePopularProModel> homePopularProModelList = new ArrayList<>();
private HomeFragPopularProAdapter homeFragPopularProAdapter;
private List<HomeFragLatestProModel> homeFragLatestProModelList = new ArrayList<>();
private HomeFragLatestProAdapter latestProAdapter;
int val = 0;
int counter;
ActivityCartBinding activity_cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
view = binding.getRoot();
intiView();
return view;
}
private void intiView() {
activity_cart = binding.layoutCart;
setCustomImage();
setPopularProducts();
setLatestPro();
binding.textLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), CartActivity.class).putExtra("value", "200"));
}
});
loadCart();
}
private void setCustomImage() {
HomeFragImageSliderModel model1 = new HomeFragImageSliderModel("https://5.imimg.com/data5/NJ/DW/YW/SELLER-8673553/namkeen-packaging-pouch-500x500.jpg", "1");
imageSliderModelList.add(model1);
HomeFragImageSliderModel model2 = new HomeFragImageSliderModel("https://5.imimg.com/data5/AV/FR/QL/SELLER-9988068/laminated-namkeen-packaging-packet-500x500.jpg", "2");
imageSliderModelList.add(model2);
HomeFragImageSliderModel model3 = new HomeFragImageSliderModel("https://thumbs.dreamstime.com/b/new-delhi-india-november-packets-chips-indian-brand-haldirams-packaged-food-182551372.jpg", "3");
imageSliderModelList.add(model3);
HomeFragImageSliderModel model4 = new HomeFragImageSliderModel("https://vinayakfoodsgroup.com/indian-ready-to-eat/wp-content/uploads/2019/07/delicious-healthy-breakfast2-4.jpg", "4");
imageSliderModelList.add(model4);
adapter = new HomeFragImageSliderAdapter(getActivity(), imageSliderModelList);
binding.autoImageSlider.startAutoCycle();
binding.autoImageSlider.setAutoCycle(true);
binding.autoImageSlider.setIndicatorAnimation(IndicatorAnimationType.WORM);
binding.autoImageSlider.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
binding.autoImageSlider.setScrollTimeInSec(3);
binding.autoImageSlider.setSliderAdapter(adapter);
}
private void setPopularProducts() {
HomePopularProModel model1 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "300", "RN Cart");
homePopularProModelList.add(model1);
HomePopularProModel model2 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "200", "RN Cart");
homePopularProModelList.add(model2);
HomePopularProModel model3 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "100", "RN Cart");
homePopularProModelList.add(model3);
HomePopularProModel model4 = new HomePopularProModel("T-Shirt", "https://png.pngtree.com/element_our/20190531/ourmid/pngtree-red-cartoon-t-shirt-image_1297508.jpg", "Available", "50", "RN Cart");
homePopularProModelList.add(model4);
homeFragPopularProAdapter = new HomeFragPopularProAdapter(getActivity(), homePopularProModelList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
SnapHelper startSnapHelper = new LinearSnapHelper();
startSnapHelper.attachToRecyclerView(binding.recyclerviewPopular);
binding.recyclerviewPopular.setLayoutManager(layoutManager);
binding.recyclerviewPopular.setItemAnimator(new DefaultItemAnimator());
binding.recyclerviewPopular.setAdapter(homeFragPopularProAdapter);
homeFragPopularProAdapter.setOnItemClickListner(new HomeFragPopularProAdapter.onItemClickListner() {
#Override
public void onClick(HomePopularProModel list) {
val = Integer.parseInt(list.getPro_price());
counter += val;
loadCart();
}
#Override
public void onCounterClick(HomePopularProModel listCounter, String from) {
if (from == "add"){
counter += Integer.parseInt(listCounter.getPro_price());
loadCart();
}else{
counter -= Integer.parseInt(listCounter.getPro_price());
loadCart();
}
}
});
}
private void setLatestPro() {
HomeFragLatestProModel model = new HomeFragLatestProModel(
"https://5.imimg.com/data5/NJ/DW/YW/SELLER-8673553/namkeen-packaging-pouch-500x500.jpg",
"Namkeen", "500gm", "Rs.350");
homeFragLatestProModelList.add(model);
HomeFragLatestProModel model2 = new HomeFragLatestProModel(
"https://5.imimg.com/data5/AV/FR/QL/SELLER-9988068/laminated-namkeen-packaging-packet-500x500.jpg",
"Sona Namkeen", "250gm", "Rs.100");
homeFragLatestProModelList.add(model2);
HomeFragLatestProModel model3 = new HomeFragLatestProModel(
"https://thumbs.dreamstime.com/b/new-delhi-india-november-packets-chips-indian-brand-haldirams-packaged-food-182551372.jpg",
"Chips", "500gm", "Rs.80");
homeFragLatestProModelList.add(model3);
HomeFragLatestProModel model4 = new HomeFragLatestProModel(
"https://thumbs.dreamstime.com/b/packets-popular-brands-snack-food-poznan-poland-jun-packets-popular-brands-snack-food-including-lays-crunchips-120285289.jpg",
"Lays", "100", "Rs.40");
homeFragLatestProModelList.add(model4);
HomeFragLatestProModel model5 = new HomeFragLatestProModel(
"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F38%2F2015%2F06%2F12233316%2FMichael-Angelo-Meal-Starter-Chicken-Bruschetta.jpg",
"Chicken Masala", "500gm", "Rs.400");
homeFragLatestProModelList.add(model5);
HomeFragLatestProModel model6 = new HomeFragLatestProModel(
"https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F38%2F2015%2F06%2F12233316%2FMichael-Angelo-Meal-Starter-Chicken-Bruschetta.jpg",
"Dry Food", "500gm", "Rs.550");
homeFragLatestProModelList.add(model6);
setDataToLatestRecycler(homeFragLatestProModelList);
}
private void setDataToLatestRecycler(List<HomeFragLatestProModel> latestProModelList) {
latestProAdapter = new HomeFragLatestProAdapter(getActivity(), latestProModelList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
binding.recyclerviewLatest.setLayoutManager(layoutManager);
binding.recyclerviewLatest.setItemAnimator(new DefaultItemAnimator());
binding.recyclerviewLatest.setAdapter(latestProAdapter);
}
public void loadCart() {
activity_cart.cartValue.setText(String.valueOf(counter));
if (counter > 0) {
binding.layoutCart.getRoot().setVisibility(View.VISIBLE);
} else {
binding.layoutCart.getRoot().setVisibility(View.GONE);
}
}
}
Adapter class
package com.example.rangeela_cart.Adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.rangeela_cart.R;
import com.example.rangeela_cart.databinding.ItemHomePopularProBinding;
import com.example.rangeela_cart.models.HomePopularProModel;
import java.util.List;
public class HomeFragPopularProAdapter extends RecyclerView.Adapter<HomeFragPopularProAdapter.myViewHolder> {
private Context context;
private List<HomePopularProModel> list;
int productSelectedNumber = 0;
public HomeFragPopularProAdapter(Context context, List<HomePopularProModel> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ItemHomePopularProBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_home_popular_pro, parent, false);
return new myViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
HomePopularProModel model = list.get(position);
Glide.with(context).load(model.getPro_image_url()).into(holder.binding.imagePopProduct);
holder.binding.textAvailability.setText(model.getPro_availability());
holder.binding.textCompanyName.setText(model.getPro_company_name());
holder.binding.textPopProductPrice.setText(model.getPro_price());
Log.e("initial counter " , String.valueOf(productSelectedNumber));
if (productSelectedNumber == 0) {
holder.binding.iconReduce.setEnabled(false);
holder.binding.layoutAddToCart.setVisibility(View.VISIBLE);
holder.binding.layoutCounter.setVisibility(View.GONE);
} else {
holder.binding.iconReduce.setEnabled(true);
holder.binding.layoutAddToCart.setVisibility(View.GONE);
holder.binding.layoutCounter.setVisibility(View.VISIBLE);
}
holder.binding.iconAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("added value ", String.valueOf(productSelectedNumber));
holder.binding.iconReduce.setEnabled(true);
productSelectedNumber += 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
onItemClickListner.onCounterClick(model, "add");
// notifyDataSetChanged();
}
});
holder.binding.iconReduce.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("reduce value = ", String.valueOf(productSelectedNumber));
if (productSelectedNumber != 0) {
productSelectedNumber = productSelectedNumber - 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
}else{
holder.binding.layoutAddToCart.setVisibility(View.VISIBLE);
holder.binding.layoutCounter.setVisibility(View.GONE);
}
onItemClickListner.onCounterClick(model, "reduce");
// notifyDataSetChanged();
}
});
holder.binding.layoutAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
productSelectedNumber = 1;
holder.binding.textCounterValue.setText(String.valueOf(productSelectedNumber));
onItemClickListner.onClick(model);
holder.binding.layoutAddToCart.setVisibility(View.GONE);
holder.binding.layoutCounter.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ItemHomePopularProBinding binding;
public myViewHolder(ItemHomePopularProBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
onItemClickListner onItemClickListner;
public void setOnItemClickListner(HomeFragPopularProAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner{
void onClick(HomePopularProModel list);
void onCounterClick(HomePopularProModel list, String str);//pass your object types.
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:orientation="vertical"
tools:context=".Fragments.HomeFragment">
<com.smarteist.autoimageslider.SliderView
android:id="#+id/autoImageSlider"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#color/white"
app:sliderAnimationDuration="200"
app:sliderAutoCycleDirection="back_and_forth"
app:sliderIndicatorAnimationDuration="600"
app:sliderIndicatorEnabled="true"
app:sliderIndicatorOrientation="horizontal"
app:sliderIndicatorPadding="5dp"
app:sliderIndicatorRadius="3dp"
app:sliderScrollTimeInSec="3"
tools:ignore="MissingClass" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Popular"
android:textColor="#color/black"
android:textSize="15sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewPopular"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:itemCount="10" />
<TextView
android:id="#+id/textLatest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="Latest"
android:textColor="#color/black"
android:textSize="15sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewLatest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:paddingBottom="15dp" />
</LinearLayout>
</ScrollView>
<include
android:id="#+id/layoutCart"
layout="#layout/activity_cart"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
i have a news app which i want when the news item (cardview) is clicked on, it should open another activity. unfortunately, nothing happens when the news item in the card view is clicked on, only when the background (recycler layout) is clicked on then the activity comes up.
i want when the news item on the cardview is clicked on, an activity should open and not when the background is clicked.
newsAdapter.java
package wami.ikechukwu.kanu;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.viewHolder> {
private ArrayList<dataModel> mDataModel;
private Context context;
private onclicklistener clicklistener;
public newsAdapter(Context context, ArrayList<dataModel> mDataModel, onclicklistener clicklistener) {
this.context = context;
this.mDataModel = mDataModel;
this.clicklistener = clicklistener;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view =
LayoutInflater.from(context).inflate(R.layout.recyclerview_layout,
viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final newsAdapter.viewHolder viewHolder, final int i) {
dataModel dataModel = mDataModel.get(i);
viewHolder.mTextView.setText(dataModel.getTitle());
viewHolder.mTextDescrip.setText(dataModel.getDescrip());
Glide.with(context).load(dataModel.getImage()).into(viewHolder.mImageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
public interface onclicklistener {
void onItemClick(int position);
}
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
}
MainActivity.java
package wami.ikechukwu.kanu;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
public class MainActivity extends AppCompatActivity implements newsAdapter.onclicklistener {
private final String KEY_AUTHOR = "author";
private final String KEY_TITLE = "title";
private final String KEY_DESCRIPTION = "description";
private final String KEY_URL = "url";
private final String KEY_URL_TO_IMAGE = "urlToImage";
private final String KEY_PUBLISHED_AT = "publishedAt";
//this string is appended to the url
String urlLink = "buhari";
ArrayList<dataModel> list;
private RecyclerView recyclerView;
private newsAdapter mAdapter;
private RecyclerView.LayoutManager mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
mAdapter = new newsAdapter(getApplicationContext(), list, this);
mLayout = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayout);
recyclerView.setAdapter(mAdapter);
jsonParser();
}
private void jsonParser() {
final AlertDialog progressDialog = new SpotsDialog(this, R.style.customProgressDialog);
progressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=655446a36e784e79b2b62adcad45be09", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
//Using a for loop to get the object (data) in the JSON
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
dataModel dataModel = new dataModel();
dataModel.setTitle(jsonObject.getString(KEY_TITLE));
dataModel.setImage(jsonObject.getString(KEY_URL_TO_IMAGE));
dataModel.setDescrip(jsonObject.getString(KEY_DESCRIPTION));
list.add(dataModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "it worked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, news_detail.class);
startActivity(intent);
}
}
recyclerview_layout.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"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/recyclerviewlayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:focusable="true"
app:cardCornerRadius="5dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical">
<TextView
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="1"
android:padding="5dp"
android:textColor="#F000"
android:textSize="17sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/layout_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="#string/Recyclerview_ImageContent"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/layout_descrip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="3"
android:padding="5dp"
android:textColor="#F000"
android:textSize="15sp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimaryDark" />
</LinearLayout>
</android.support.v7.widget.CardView>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
In order to set onclick listener in recycler view, you have to follow as below
inner class ViewHolderItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
clicklistener.onItemClick(adapterposition)
}
}
}
OnclickListener will work in Init block
I think should add setOnClickListener method in an onBindViewHolder
And in that you should call another activity with passing your parameter.
Example :- (in onBindViewHolder)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call activity.
Intent intent = new Intent(activity, anotherActivityname.class);
// For passing values
intent.putExtra(key,value);
startActivity(intent);
}
});
You have to modify your viewHolder in newsAdapter like following.
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public CardView yourCardView;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
yourCardView= itemView.findViewById(R.id.recyclerviewlayout);
// here you set on click listerner to your cardview.
yourCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
Hope it helps you.
How to make a specific item respond to click in recyclerView?
So for this make your card view clickable false and make your new item(View inside cardview) clickable true:
<Cardview..
android:clickable="false">
...............
......
<View..
android:clickable="true"/>
</Cardview>
I am working on an Android Project to display Github repo details.
I am trying to first select org name for a particular company, like Amazon has orgs on Github like AWS, AMZN, AWSLABS etc.
For this I first create a List of clickable buttons via RecyclerView(which works).
Then when user clicks on a particular org_name, the App does a HTTP request to Github to fetch relevant info and display inside a fragment which uses another RecyclerView(not working RecyclerViewRepoAdapter.java).
This part does not work as onCreateViewHolder or onBindViewHolder is not called (getItemCount is called and returns correct length)
Tried some of the suggestions mentioned like in this link! but it didn't work.
Any help is appreciated!
OrganizationInfo.java // Driver program
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class OrganizationInfo extends AppCompatActivity {
private String companyName;
private String companyAddress;
private List<String> orgNames;
private TextView companyNameTV;
private TextView companyAddressTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_info);
getCompanyData();
companyNameTV = findViewById(R.id.companyNameTv);
companyAddressTV = findViewById(R.id.companyAddressTv);
companyNameTV.setText(companyName);
companyAddressTV.setText(companyAddress);
initRecyclerView();
}
private void getCompanyData() {
companyName = "amazon";
companyAddress = "207 Boren Ave N, Seattle, WA 98109";
orgNames = new ArrayList<>();
orgNames.add("amzn");
orgNames.add("aws");
orgNames.add("awslabs");
}
private void initRecyclerView(){
// Log.d(TAG, "initRecyclerView: init recyclerview");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.orgListRecyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewOrgAdapter adapter = new RecyclerViewOrgAdapter(this, orgNames);
recyclerView.setAdapter(adapter);
}
}
GithubFragment.java
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class GithubFragment extends Fragment {
private List<Repository> repositories = new ArrayList<>();
RecyclerView recyclerView;
RecyclerViewRepoAdapter listAdapter;
public GithubFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
if (getArguments() != null) {
String orgName = getArguments().getString("org_name");
GraphQLAsyncTask graphQLAsyncTask = new GraphQLAsyncTask();
graphQLAsyncTask.execute(orgName, "");
}
}
private class GraphQLAsyncTask extends AsyncTask<String, String, String> {
private String response;
private Reader in;
#Override
protected String doInBackground(String... body) {
Map<String, String> params = new HashMap<>();
params.put("company", body[0]);
params.put("language", body[1]);
StringBuilder postData = new StringBuilder();
try{
for (Map.Entry param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey().toString(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String url = "https://****************/getOrgReposGraphQL";
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.getOutputStream().write(postDataBytes);
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0; )
sb.append((char) c);
response = sb.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
ParseResponse parseResponse = new ParseResponse(response);
repositories.addAll(parseResponse.getRepositories());
listAdapter.notifyDataSetChanged();
}
}
}
RecyclerViewRepoAdapter.java // Problematic Adapter
package edu.neu.madcourse.goexplore;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewRepoAdapter extends RecyclerView.Adapter<RecyclerViewRepoAdapter.ListViewHolder> {
private List<Repository> mRepositories;
private Context mContext;
private int mCounter = 1;
public RecyclerViewRepoAdapter(Context context, List<Repository> repos) {
mRepositories = repos;
mContext = context;
}
#NonNull
#Override
public ListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_repo, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ListViewHolder holder, int position) {
Repository repo = mRepositories.get(position);
holder.repoTV.setText(repo.getNameWithOwner());
holder.repoLangugeTV.setText(repo.getPrimaryLanguage());
holder.repoStarsTV.setText(repo.getStargazers());
holder.repoCounter.setText(String.valueOf(mCounter++) + ".");
}
#Override
public int getItemCount() {
return mRepositories.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView repoTV;
TextView repoLangugeTV;
TextView repoStarsTV;
TextView repoCounter;
public ListViewHolder(View itemView) {
super(itemView);
repoTV = itemView.findViewById(R.id.repo_name_row);
repoLangugeTV = itemView.findViewById(R.id.repo_language_tv);
repoStarsTV = itemView.findViewById(R.id.repo_stars_tv);
repoCounter = itemView.findViewById(R.id.repo_list_number);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
}
RecyclerViewOrgAdapter.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewOrgAdapter extends RecyclerView.Adapter<RecyclerViewOrgAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewOrgAdapter";
private List<String> orgs;
private Context context;
public RecyclerViewOrgAdapter(Context context, List<String> orgs) {
this.orgs = orgs;
this.context = context;
}
#NonNull
#Override
public RecyclerViewOrgAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.organization_id_relative_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewOrgAdapter.ViewHolder holder, final int position) {
holder.orgIdBtn.setText(orgs.get(position));
holder.orgIdBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity activity = (AppCompatActivity) v.getContext();
Fragment githubFragment = new GithubFragment();
Bundle bundle = new Bundle();
bundle.putString("org_name", orgs.get(position));
githubFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.github_fragment, githubFragment).addToBackStack(null).commit();
}
});
}
#Override
public int getItemCount() {
return orgs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
Button orgIdBtn;
public ViewHolder(View itemView) {
super(itemView);
orgIdBtn = itemView.findViewById(R.id.orgIdBtn);
}
}
}
list_item_repo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/repo_list_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="1."
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/repo_name_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:text="Repo Name"
android:textSize="24sp"
app:layout_constraintStart_toEndOf="#+id/repo_list_number"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView2"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="#+id/repo_name_row"
app:layout_constraintTop_toBottomOf="#+id/repo_name_row"
app:srcCompat="#mipmap/star_dark_round" />
<TextView
android:id="#+id/repo_stars_tv"
android:layout_width="42dp"
android:layout_height="33dp"
android:layout_marginStart="16dp"
android:text="1441"
app:layout_constraintBottom_toBottomOf="#+id/imageView2"
app:layout_constraintStart_toEndOf="#+id/imageView2"
app:layout_constraintTop_toTopOf="#+id/imageView2" />
<TextView
android:id="#+id/repo_language_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:text="Ruby"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/repo_stars_tv"
app:layout_constraintStart_toEndOf="#+id/repo_stars_tv"
app:layout_constraintTop_toTopOf="#+id/repo_stars_tv" />
</LinearLayout>
</LinearLayout>
fragment_github.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GithubFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/repo_recycler_view"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" />
</LinearLayout>
You are attaching adapter after getting a response from the API
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
Move this code in onCreateView
assert getArguments() != null;
View v = inflater.inflate(R.layout.fragment_github, container, false);
recyclerView = v.findViewById(R.id.repo_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
listAdapter = new RecyclerViewRepoAdapter(getContext(), repositories); // List of Github repos to be display
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(listAdapter); // Called from here after response from cloud funtion
return v;
And after getting a response from Api in AsyncTask onPostExecute() Method add data into list and notify adapter
ParseResponse parseResponse = new ParseResponse(response);
repositories = parseResponse.getRepositories();
listAdapter.notifyDataSetChanged();
I have a problem binding a listview with ArrayList. When the first Vegetable Category is clicked it should bring different 3 elements in the listview but only the first one is displayed on the listview the others didn't show up.
here is my code (I am new to android stuff)!!!!!!
it should bring the list like this
enter image description here
problem_list.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">
<ImageView
android:id="#+id/problem_imageView"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="13dp"
android:layout_marginTop="13dp" />
<!--app:srcCompat="#drawable/pest" />-->
<TextView
android:id="#+id/englishName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/problem_imageView"
android:layout_marginStart="13dp"
android:layout_toEndOf="#+id/problem_imageView"
android:fontFamily="monospace"
android:text="Category English Name"
android:textAppearance="#style/TextAppearance.AppCompat.Medium" />
<TextView
android:id="#+id/amharicName_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/englishName_textView"
android:layout_below="#+id/englishName_textView"
android:layout_marginTop="4dp"
android:fontFamily="monospace"
android:text="Amharic Name"
android:textColor="#000080"
android:textSize="15sp" />
<TextView
android:id="#+id/count_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/amharicName_textView"
android:layout_below="#+id/amharicName_textView"
android:layout_marginTop="8dp"
android:fontFamily="monospace"
android:text="Count"
android:textColor="#000080"
android:textSize="14sp" />
</RelativeLayout>
ProblemAdapter.java
package com.packageName;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ProblemAdapter extends BaseAdapter {
private Context context;
private ArrayList<Integer> listID;
private ArrayList<String> English_Title;
private ArrayList<String> Amharic_Title;
private ArrayList<Integer> count;
public ProblemAdapter(Context context, ArrayList<Integer> listID,
ArrayList<String> name,ArrayList<String> Amharic_Title,ArrayList<Integer>
count) {
this.context = context;
this.listID = listID;
this.English_Title = name;
this.Amharic_Title= Amharic_Title;
this.count = count;
}
#Override
public int getCount() {
return English_Title.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;
}
}
problem_category.java
package com.packageName;
import android.content.Intent;
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.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class problem_category extends AppCompatActivity {
String VegetableCategoryType ;
ListView listView;
ArrayList<Integer> ImageID;
ArrayList<String> English_Title;
ArrayList<String> Amharic_Title;
ArrayList<Integer> count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_category);
// Assigning caller plant to the VegetableCategoryType
Intent intent = getIntent();
VegetableCategoryType = intent.getStringExtra("Plant_Name");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Will be replaced with new action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView = findViewById(R.id.category_List_view);
ImageID = new ArrayList<>();
English_Title = new ArrayList<>();
Amharic_Title = new ArrayList<>();
count = new ArrayList<>();
ImageID = getImageID();
English_Title = getEnglishName();
Amharic_Title = getAmharicName();
count = getCount();
ProblemAdapter pAdapter = new ProblemAdapter(problem_category.this,
ImageID,English_Title,Amharic_Title,count);
listView.setAdapter(pAdapter);
}
#Override
public void finish(){
super.finish();
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
public ArrayList<String> getEnglishName(){
English_Title= new ArrayList<>();
English_Title.add("Pest");
English_Title.add("Disease");
English_Title.add("Disorder");
return English_Title;
}
private ArrayList<String> getAmharicName() {
Amharic_Title= new ArrayList<>();
Amharic_Title.add("sub-title1");
Amharic_Title.add("sub-title2");
Amharic_Title.add("sub-title3");
return Amharic_Title;
}
public ArrayList<Integer> getImageID(){
ImageID = new ArrayList<>();
ImageID.add(R.drawable.pest);
ImageID.add(R.drawable.disease);
ImageID.add(R.drawable.disorder_edited);
return ImageID;
}
public ArrayList<Integer> getCount(){
count = new ArrayList<>();
if(VegetableCategoryType == "Cabbage"){
count.add(3);
count.add(8);
count.add(3);
}else if (VegetableCategoryType =="Pepper"){
count.add(7);
count.add(5);
count.add(2);
}else if(VegetableCategoryType == "Onion"){
count.add(2);
count.add(5);
count.add(3);
}else if(VegetableCategoryType == "Tomato"){
count.add(8);
count.add(16);
count.add(5);
}
return count;
}
}
MainActivity click_Listners()
public void click_Listeners(){
cabbageImageView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent pCategory = new
Intent(getApplicationContext(),problem_category.class);
pCategory.putExtra("Plant_Name","Cabbage");
startActivity(pCategory);
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
You are not setting the values for the new views created. Your getView body should look like this:
if (convertView == null) {
convertView = View.inflate(context, R.layout.problem_list, null);
} else {
ImageView img = convertView.findViewById(R.id.problem_imageView);
TextView txtView_Eng =
convertView.findViewById(R.id.englishName_textView);
//TextView txtView_Amc =
convertView.findViewById(R.id.amharicName_textView);
TextView txtView_Count =
convertView.findViewById(R.id.count_textView);
img.setImageResource(listID.get(position));
txtView_Eng.setText(English_Title.get(position));
txtView_Amc.setText(Amharic_Title.get(position));
txtView_Count.setText(count.get(position));
}
return convertView;
I want my 2 columns RecyclerView, i.e. using GridLayoutManager, inside scrollview. I found a way to put single column recyclerview inside scrollview from this link, but i cant figure out how to put Grid RecyclerView inside scrollview.
I found solution. Work perfect for me.
my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_grid_recycler_view"
tools:context="com.example.recyclerview_horizontal.GridRecyclerView">
<ScrollView
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
android:layout_marginBottom="50dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
MainActivity
package com.example.gridrecyclerviewscroll;
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.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements RecyclerAdapter.DynamicHeight {
RecyclerView recyclerView;
RecyclerAdapter adapter;
ArrayList<Integer> list;
ArrayList<Integer> size;
TextView txt;
long sumHeight=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager lm = new GridLayoutManager(this,2);
// txt = (TextView) findViewById(R.id.txt1);
recyclerView.setLayoutManager(lm);
size = new ArrayList<>();
list = new ArrayList<>();
list.add(R.drawable.index1);
list.add(R.drawable.index2);
list.add(R.drawable.index3);
list.add(R.drawable.index4);
list.add(R.drawable.index5);
list.add(R.drawable.index6);
list.add(R.drawable.index8);
list.add(R.drawable.index9);
list.add(R.drawable.index10);
adapter = new RecyclerAdapter(list,this);
recyclerView.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 void HeightChange(int position, int height) {
size.add(height);
sumHeight = calSum();
float density = this.getResources().getDisplayMetrics().density;
float viewHeight = sumHeight * density;
recyclerView.getLayoutParams().height = (int) sumHeight;
}
private long calSum() {
long tot=0;
for(int i=0;i<size.size();i++){
tot = tot + size.get(i);
}
return tot;
}
#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);
}
}
RecyclerViewAdapter
package com.example.gridrecyclerviewscroll;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nteam on 23/10/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Integer> list;
Context context;
private DynamicHeight dynamicHeight;
public RecyclerAdapter(ArrayList<Integer> list, DynamicHeight dynamicHeight){
this.list = list;
this.dynamicHeight = dynamicHeight;
}
public RecyclerAdapter(ArrayList<Integer> list){
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_card,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.img.setImageResource(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
public ViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img_thumbnail);
}
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position, List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.itemView.post(new Runnable() {
#Override
public void run() {
int cellwidth = holder.itemView.getWidth();
int cellheight = holder.itemView.getHeight();
if(dynamicHeight!=null) dynamicHeight.HeightChange(position, cellheight);
}
});
}
public interface DynamicHeight {
void HeightChange(int position, int height);
}
}
All credits goes to #Ashkan