In my Application I m having a RecyclerView in one of my Fragments in which I am getting response from a server using Reterofit. Every thing is fine but My RecylerView is not displaying any data returned from my service. Even the
int count = offerRecyclerAdapter.getItemCount();
of my adapter is returning the correct amount of data count returned from server.
Inside Fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
offersRecyclerView = (RecyclerView) view.findViewById(R.id.offer_recycler);
MotorCityArabiaGlobal global = (MotorCityArabiaGlobal) getActivity().getApplication();
ApiInterface apiService=global.getClient().create(ApiInterface.class);
Call<OfferResponse> call = apiService.getOffers(4);
call.enqueue(new Callback<OfferResponse>() {
#Override
public void onResponse(Call<OfferResponse> call, Response<OfferResponse> response) {
OfferResponse offers = response.body();
if(offers!=null){
List<Offer> result = response.body().getResult();
offerRecyclerAdapter = new OffersAdapter(getActivity(),result);
offersRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
offersRecyclerView.setItemAnimator(new DefaultItemAnimator());
offersRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
offersRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
int count = offerRecyclerAdapter.getItemCount();
offerRecyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<OfferResponse> call, Throwable t) {
}
});
}
Adapter Class:
public class OffersAdapter extends RecyclerView.Adapter<OffersAdapter.MyViewHolder> {
private List<Offer> offersList= Collections.emptyList();
private LayoutInflater inflater;
Context ctx;
public OffersAdapter(Context ctx,List<Offer> offersList) {
this.ctx = ctx;
this.inflater = LayoutInflater.from(ctx);
this.offersList = offersList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.offer_list_layout, parent, false);
View view = inflater.inflate(R.layout.offer_list_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Offer offer = offersList.get(position);
holder.title.setText(offer.getOffer_title());
holder.price.setText(offer.getPrice());
holder.offerCount.setText(offer.getOffer_count());
}
#Override
public int getItemCount() {
return offersList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, offerCount, price;
public ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
offerCount = (TextView) view.findViewById(R.id.offer_count);
price = (TextView) view.findViewById(R.id.price);
image = (ImageView)view.findViewById(R.id.car_img);
}
}
}
home_layout.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="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/header_wrapper"
>
<!-- Row1-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<!-- Column1 row 1-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/new_car_selector"
android:clickable="true"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
></LinearLayout>
<!-- Column2 row 1-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/find_car_selector"
android:clickable="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
></LinearLayout>
</LinearLayout>
<!-- Row2-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>
<!-- Column1 row 2-->
<!-- Column2 row 2-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/sell_car_selector"
android:clickable="true"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
></LinearLayout>
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/compare_car_selector"
android:clickable="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
></LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- Header Wrapper ends-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header_wrapper"
android:id="#+id/offers_recycler_wrapper"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CAR OFFERS"
android:textColor="#color/colorAccentDark"
android:textStyle="bold"
android:textSize="16sp"
android:layout_marginLeft="5dp"
/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/offer_recycler"
></android.support.v7.widget.RecyclerView>
</LinearLayout>
</RelativeLayout>
offer_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="match_parent"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical"
android:paddingTop="6dp"
android:paddingBottom="5dp"
>
<ImageView
android:layout_width="80dp"
android:layout_height="60dp"
android:src="#drawable/sell_car_select"
android:id="#+id/car_img"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/meta_data"
android:orientation="vertical"
android:layout_toEndOf="#id/car_img"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="16dp"
android:textColor="#000"
android:textStyle="bold"
android:id="#+id/title"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="3dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/price"
android:text="13,000"
android:textStyle="bold"
android:textColor="#color/colorAccentDark"
android:textSize="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/curr"
android:textColor="#BDBDBD"
android:text=" SAUDI RAYAL"
android:textSize="12dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/offer_count_wrapper"
android:orientation="horizontal"
android:layout_marginTop="3dp"
>
<ImageView
android:layout_width="12dp"
android:layout_height="12dp"
android:src="#drawable/ic_offer_orange"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:text=" 3 Offers"
android:id="#+id/offer_count"
/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
add the line below in your onResponse after offersRecyclerView.addItemDecoration();
offersRecyclerView.setAdapter(offerRecyclerAdapter);
hope this helps.
You did not set the adapter to the RecyclerView. Use setAdapter method. See the following code,
List<Offer> results = new ArrayList<Offer>();
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
offersRecyclerView = (RecyclerView) view.findViewById(R.id.offer_recycler);
offersRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
offersRecyclerView.setItemAnimator(new DefaultItemAnimator());
offersRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
offerRecyclerAdapter = new OffersAdapter(getActivity(), results)
offersRecyclerView.setAdapter(offerRecyclerAdapter);
offersRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
MotorCityArabiaGlobal global = (MotorCityArabiaGlobal) getActivity().getApplication();
ApiInterface apiService=global.getClient().create(ApiInterface.class);
Call<OfferResponse> call = apiService.getOffers(4);
call.enqueue(new Callback<OfferResponse>() {
#Override
public void onResponse(Call<OfferResponse> call, Response<OfferResponse> response) {
OfferResponse offers = response.body();
if(offers != null){
List<Offer> result = response.body().getResult();
results.clear();
results.addAll(result);
offerRecyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<OfferResponse> call, Throwable t) {
}
});
}
Related
My app has a RawMaterialFragment that displays raw materials data in a recyclerView from room database.
I am trying to build a detail activity(MetrialItemView) to show up the details of an individual raw material by clicking or selecting the raw material from the recyclerView.
my problem is how to send the data from the adapter and how to receive the data in the MetrialItemView Activity and display it.
MaterialListAdapter:
public class MaterialListAdapter extends RecyclerView.Adapter<MaterialListAdapter.ViewHolder> {
private final LayoutInflater mInflater;
private FragmentRawMaterials mContext;
private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
RawMaterialsEntity mCurrent;
public MaterialListAdapter(FragmentRawMaterials context) {
mInflater = LayoutInflater.from(context.getActivity());
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(itemView);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final TextView materialName;
private final TextView materialBrand;
private final TextView materialQuantity;
LinearLayout parentLayout;
private ViewHolder(View itemView) {
super(itemView);
materialName = itemView.findViewById(R.id.raw_material_name);
materialBrand = itemView.findViewById(R.id.raw_material_brand);
materialQuantity = itemView.findViewById(R.id.raw_material_quantity);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (mMaterial != null) {
mCurrent = mMaterial.get(position);
holder.materialName.setText(mCurrent.getRawMaterialName());
holder.materialBrand.setText(mCurrent.getRawMaterialBrand());
holder.materialQuantity.setText(String.valueOf(mCurrent.getRawMaterialQuantity()));
} else {
// Covers the case of data not being ready yet.
holder.materialName.setText("Name NA");
holder.materialBrand.setText("Brand NA");
holder.materialQuantity.setText("Quantity NA");
}
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
mContext.startActivity(intent);
}
});
}
public void setMaterial(List<RawMaterialsEntity> materials){
mMaterial = materials;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't return null).
#Override
public int getItemCount() {
if (mMaterial != null)
return mMaterial.size();
else return 0;
}
}
MaterialItemView:
public class MaterialItemView extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_item_view);
}
}
material_list_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Name:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Raw Material Brand:"
style="#style/OtherTextViews"/>
<TextView
android:id="#+id/material_brand_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Weight:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2000"
style="#style/OtherTextViewsBody"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="gm"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Unit Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cost per gm/ml:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.1"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Available Quantity:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Cost:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="50000"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Name:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Email:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pandah#panadh.com"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supplier Phone:"
style="#style/OtherTextViews"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+966555699517"
style="#style/OtherTextViewsBody"/>
</LinearLayout>
</LinearLayout>
FragmentRawMaterials:
public class FragmentRawMaterials extends Fragment{
private RawMaterialViewModel mMaterialViewModel;
private static final int NEW_MATERIAL_ACTIVITY_REQUEST_CODE = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_raw_materials, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
//FloatingActionButton fab to insert recipes
TextView emptyViewText = view.findViewById(R.id.empty_raw__materials_view);
FloatingActionButton fab = view.findViewById(R.id.fab_raw_materials);
fab.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), RawMaterialsEditor.class);
startActivityForResult(intent, NEW_MATERIAL_ACTIVITY_REQUEST_CODE);
});
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
//Decoration to add a line divider between recyclerView items
DividerItemDecoration decoration =
new DividerItemDecoration(Objects.requireNonNull(this.getActivity()),
R.drawable.border_line);
recyclerView.addItemDecoration(decoration);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
final MaterialListAdapter adapter = new MaterialListAdapter(this);
recyclerView.setAdapter(adapter);
// Check if adapter list is empty, if so empty text view will appear.
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
super.onChanged();
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
emptyViewText.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emptyViewText.setVisibility(View.GONE);
}
}
});
mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
// Update the cached copy of the words in the adapter.
mMaterialViewModel.getAllMaterials().observe(this, adapter::setMaterial);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NEW_MATERIAL_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
RawMaterialsEntity material = new RawMaterialsEntity(data
.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_BRAND),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_WEIGHT)),
Float.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_COST)),
Integer.valueOf(data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_QUANTITY)),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_NAME),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_EMAIL),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_S_PHONE),
data.getStringExtra(RawMaterialsEditor.EXTRA_REPLY_UOM));
mMaterialViewModel.insertMaterial(material);
mMaterialViewModel.costPerGm();
mMaterialViewModel.totalCost();
} else {
Toast.makeText(
Objects.requireNonNull(getActivity()).getApplicationContext(),
R.string.editor_insert_rm_failed,
Toast.LENGTH_LONG).show();
}
}
}
each row of dataModel() must have ID and then use putExtra() whan clicked It happens
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
intent.putExtra("ID",mCurrent.getID());
mContext.startActivity(intent);
}
});
and use getIntent() in detailActivity
int id =getIntent().getIntExtra("ID",-1);
and then get a row data in detail activity from database(viewModel)by ID and parse it
Am trying to build my first app and my recyclerView only displays the first item from the json.I have tried changing the layout height to wrap_content but its still not working
Here is the xml layout for the recyclerview activity
<?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="wrap_content"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
the cardview xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
cardview:cardCornerRadius="2dp"
cardview:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:paddingBottom="15dp">
<TextView
android:id="#+id/car_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:fontFamily="sans-serif-smallcaps"
android:text="Car Name"
android:textColor="#996515"
android:textSize="24sp"
android:textStyle="bold" />
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/Car_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="#+id/car_name"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp" />
<TextView
android:id="#+id/tvfeature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginTop="25dp"
android:layout_toRightOf="#+id/car_name"
android:text="Features"
android:textColor="#000"
android:textSize="22sp" />
<View
android:layout_width="100dp"
android:layout_height="1dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/Car_image"
android:background="#000" />
<ImageView
android:id="#+id/ac"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/air_conditioner" />
<TextView
android:id="#+id/feature1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvfeature"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/ac"
android:text="Air conditioner"
android:textColor="#000"
android:textSize="16sp" />
<ImageView
android:id="#+id/tr"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/feature1"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/transmission" />
<TextView
android:id="#+id/feature2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature1"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/tr"
android:text="Manual"
android:textColor="#333333"
android:textSize="16sp" />
<ImageView
android:id="#+id/pass"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tr"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/passengers" />
<TextView
android:id="#+id/feature3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature2"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/pass"
android:text="6 Passengers"
android:textColor="#333333"
android:textSize="16sp" />
<TextView
android:id="#+id/pricetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:text="Price :"
android:textColor="#333333"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/car_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:layout_marginLeft="2dp"
android:layout_toRightOf="#+id/pricetxt"
android:text="KSH.2000"
android:textColor="#996515"
android:textSize="22sp" />
<TextView
android:id="#+id/organiser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginTop="5dp"
android:text="Owner :"
android:textColor="#333333"
android:textSize="14sp" />
<TextView
android:id="#+id/crAgent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginLeft="2dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#+id/organiser"
android:layout_toRightOf="#+id/organiser"
android:text="Supercars Rentals"
android:textColor="#05056c"
android:textSize="14sp" />
<Button
android:id="#+id/btn_rent"
style="#style/AppTheme.ButtonCorners"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/Car_image"
android:layout_marginRight="12dp"
android:clickable="true"
android:text="Rent"
android:textColor="#eef525" />
<TextView
android:id="#+id/car_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</RelativeLayout>
</android.support.v7.widget.CardView>
The cars.java class to load items into the recyclerview
public class cars extends AppCompatActivity {
String url = "http://192.168.43.201/Car_rental/retrievecars.php";
Context context = null;
ProgressDialog dialog;
private List<CarsItem> array_cars = new ArrayList<>();
AdapterClass adapter;
NetworkImageView carsImageview;
private String user_Location = "cLocation";
private String Category = "category";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cars);
adapter = new AdapterClass(cars.this, array_cars);
RecyclerView recycler = (RecyclerView) findViewById(R.id.rv);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
setCars();
recycler.addOnItemTouchListener(new RecyclerTouchListener(this, recycler, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void setCars() {
dialog = new ProgressDialog(this);
dialog.setMessage("Loading cars...");
dialog.show();
if (array_cars != null) {
array_cars.clear();
}
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
hideDialog();
Log.d("Sever Message", s);
JSONObject cars = new JSONObject(s);
JSONArray jsonArray = cars.getJSONArray("Cars");
JSONObject jobject = null;
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
jobject = jsonArray.getJSONObject(i);
CarsItem carsdata = new CarsItem();
carsdata.setId(jobject.getString("0"));
carsdata.setCarname(jobject.getString("1"));
carsdata.setImages(jobject.getString("car_image"));
carsdata.setfeature1(jobject.getString("5"));
carsdata.setfeature2(jobject.getString("6"));
carsdata.setfeature3(jobject.getString("7"));
carsdata.setPrice(jobject.getString("8"));
array_cars.add(carsdata);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Getting Image Location & category
String Location = "";
String Ccategory = "cars";
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(Category, Ccategory);
params.put(user_Location, Location);
//returning parameters
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
// requestQueue.add(request);
AppController.getmInstance().addToRequestQueue(request);
}
public void hideDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
GestureDetector gestureDetector;
cars.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final cars.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {
View child = recycler.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recycler.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
and finally my adapter class
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.CustomViewHolder> {
private List<CarsItem> Array_cars;
private ImageLoader imageLoader;
private Context mContext;
public AdapterClass(Context context, List<CarsItem> array_cars) {
this.Array_cars = array_cars;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_design, null);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder,final int i) {
final CarsItem carsItem = Array_cars.get(i);
holder.imageUrl = carsItem.getImages();
imageLoader = AppController.getmInstance().getmImageLoader();
holder.Carname.setText(carsItem.getCarname());
holder.feature1.setText(carsItem.getfeature1());
holder.feature2.setText(carsItem.getfeature2());
holder.feature3.setText(carsItem.getfeature3());
holder.price.setText(carsItem.getPrice());
holder.agent.setText(carsItem.getcarowner());
holder.carid.setText(carsItem.getId());
holder.carimage.setImageUrl("http://192.168.43.201/Car_rental/cars/"+carsItem.getImages(), imageLoader);
holder.rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, HireCar.class);
intent.putExtra("carname",carsItem.getCarname());
intent.putExtra("car_rate",carsItem.getPrice());
intent.putExtra("car_image", carsItem.getImages());
intent.putExtra("car_id", carsItem.getId());
intent.putExtra("c_owner", carsItem.getcarowner());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != Array_cars ? Array_cars.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
String imageUrl;
TextView Carname, feature1, feature2, feature3, price,agent,carid;
NetworkImageView carimage;
Button rent;
public CustomViewHolder(View view) {
super(view);
this.Carname = (TextView) view.findViewById(R.id.car_name);
this.feature1 = (TextView) view.findViewById(R.id.feature1);
this.feature3 = (TextView) view.findViewById(R.id.feature3);
this.price = (TextView) view.findViewById(R.id.car_price);
this.feature2=(TextView) view.findViewById(R.id.feature2);
this.carimage = (NetworkImageView) view.findViewById(R.id.Car_image);
this.rent=(Button)view.findViewById(R.id.btn_rent);
this.agent=(TextView)view.findViewById(R.id.crAgent);
this.carid=(TextView)view.findViewById(R.id.car_id);
}
}
}
I think the problem is that you are not adding the elements to the adapter. You need to have a method in the adapter to add items after the adapter has been created. Inside that method you need to notify. Example:
void addItems(List<CarItem> carItems){
Array_cars.addAll(carItems);
notifyDataSetChanged();
}
However, I would go a bit far and find the number of items and try to notify only for the newly inserted ones(in case there is something already).
This can be done like this:
void addItems(List<CarItem> carItems){
int position = Array_cars.size();
Array_cars.addAll(carItems);
notifyItemRangeChanged(position, Array_cars.size() - position);
}
EDIT
Look at this example below:
RecycleView
Here is the xml layout for the recyclerview activity
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
You have added match_parent height of "RecyclerView" please change to wrap_content.
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
i am trying to switch setLayoutManager between LinearLayoutManager(List) to GridLayoutManager(GridView) on toggle button it is working fine but when the layout changes for list to grid its giving me an exception in list view i am showing extra data than girdView and setting texts cant not find this Textviews in gridView single item file so its giving me an error can you please guide how can i handle two layouts and views in single Adapter
this is my Adapter Code
public class SavedAlbumAdapter2 extends RecyclerView.Adapter<SavedAlbumAdapter2.ItemViewHolder> {
private final GlideRequest<Drawable> request;
private ArrayList<AlbumLocalObj> itemModels;
private static final int LIST_ITEM = 0;
private static final int GRID_ITEM = 1;
private ClickListener mListener;
private LocalPreferences localPreferences;
public SavedAlbumAdapter2(Activity context, ArrayList<AlbumLocalObj> values, ClickListener clickListener) {
itemModels = values;
this.mListener = clickListener;
localPreferences = new LocalPreferences(context);
int reqWidth = ((HomeActivity) context).screenWidth / 2;
request = GlideApp.with(context)
.asDrawable()
.centerCrop()
.override(reqWidth, reqWidth)
.transition(withNoTransition());
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == LIST_ITEM) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_gallery2, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_gallery, parent, false);
}
return new ItemViewHolder(itemView, mListener);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
AlbumLocalObj model = itemModels.get(position);
holder.img_label.setText(model.getName());
holder.tv_count.setText(String.valueOf(model.getCount()));
initializeViews(model, holder, position);
}
#Override
public int getItemViewType(int position) {
if (localPreferences.isGridViewEnabled()) {
return GRID_ITEM;
} else {
return LIST_ITEM;
}
}
private void initializeViews(AlbumLocalObj model, final ItemViewHolder holder, int position) {
if (model.getMediaFileObject() == null)
holder.gallery_img.setImageResource(R.drawable.ic_empty_fol);
else {
request.load(model.getMediaFileObject()).listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
Log.i("glide_action", "failure");
clearResource((MediaFileObject) model);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
clearResource((MediaFileObject) model);
Log.i("glide_action", "success");
return false;
}
})
.into(holder.gallery_img);
}
}
public interface ClickListener {
void onItemClick(View view, int piecesAtPos);
void onItemLongClick(View view, int piecesAtPos);
}
private void clearResource(MediaFileObject item) {
try {
if (item.getInputStream() != null) {
Log.i("resource", "clear");
item.getInputStream().close();
item.setInputStream(null);
//Log.i("closing_str", pos + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return itemModels.size();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
SquarImageView gallery_img;
TextView img_label;
TextView tv_count;
ImageButton info;
private ClickListener mListener;
ItemViewHolder(View itemView, ClickListener listener) {
super(itemView);
gallery_img = itemView.findViewById(R.id.img);
info = itemView.findViewById(R.id.info);
img_label = itemView.findViewById(R.id.label);
tv_count = itemView.findViewById(R.id.count);
this.mListener = listener;
info.setOnClickListener(this);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
mListener.onItemClick(view, getAdapterPosition());
}
#Override
public boolean onLongClick(View view) {
mListener.onItemLongClick(view, getAdapterPosition());
return false;
}
}
}
this is my layout for single item of grid View
<LinearLayout 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/content_add_messages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<SquarImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:padding="0dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img"
android:alpha="0.8"
android:background="#color/darkColor"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:padding="7dp">
<TextView
android:id="#+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:ellipsize="end"
android:maxLines="1"
android:singleLine="true"
android:text="akhskajhskjahkasjkhajskhjksasahjksahjkshajksahkjsahkjshjksjhakjhskjah"
android:textColor="#android:color/white"
android:textSize="16sp" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="lahslahashkjjsahshjaksjhaksajhksahkjsahjksahkjsahjksahkjsahkjsahjksajhksahkjsakhjsahkjsahkjsahsklhask"
android:textColor="#android:color/white"
android:textSize="12sp" />
</LinearLayout>
<ImageButton
android:id="#+id/info"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?android:attr/selectableItemBackground"
android:padding="7dp"
app:srcCompat="#drawable/info_white" />
</LinearLayout>
</RelativeLayout>
and this is for list item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<RelativeLayout
android:id="#+id/parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
android:background="#drawable/album_item_background" />
<RelativeLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/album_item_background">
<SquarImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:scaleType="fitXY" />
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kajhskahskhas" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kajhskahskhas" />
<TextView
android:id="#+id/3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
</LinearLayout>
<LinearLayout
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/info"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/info"
android:background="?attr/selectableItemBackgroundBorderless"
/>
</LinearLayout>
in my list view there are extra textview and button when i change list view to grid it can not find that views what should i do? do i have to create separate adapter?or how can i handle this in single adapter please help me
Why do the extra TextViews in List item layout is having the same id?
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kajhskahskhas" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kajhskahskhas" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
am trying to click button in Recyclerview item but it not receive onclick event.but it worked for double tap to respond onclick listener
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="62dp"
android:layout_height="62dp"
android:layout_marginRight="5dp"
android:focusableInTouchMode="false"
android:scaleType="fitXY"
android:layout_marginLeft="5dp"
android:id="#+id/calllog_contact_img"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calllog_contact_name"
android:layout_marginBottom="2dp"
android:text="Pounkumar Purushothaman"
android:textSize="18dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="20dp"
android:focusableInTouchMode="false"
android:src="#android:drawable/sym_call_incoming"
android:layout_marginBottom="10dp"
android:id="#+id/calllog_call_type"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/calllog_no"
android:text="+919043974134"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10:20"
android:layout_marginRight="20dp"
android:id="#+id/calllog_call_duration"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10:20"
android:id="#+id/calllog_call_timing"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/llExpandArea"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:gravity="center"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:id="#+id/call_txt"
android:text="Call" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:paddingLeft="15dp"
android:id="#+id/block_txt"
android:text="Msg" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
am trying to click button in Recyclerview item but it not receive onclick event.but it worked for double tap to respond onclick listener
Adapter:
public class calllog_customadapter extends RecyclerView.Adapter<calllog_customadapter.RecordHolder> {
private List<calllog_item> calllog_items;
Context c;
RecyclerView list;
private int expandedPosition = -1;
#Override
public RecordHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.calllog_item, parent, false);
return new RecordHolder(itemView);
}
calllog_customadapter(Context context, RecyclerView list, final List<calllog_item> calllog_item){
this.c=context;
this.list=list;
this.calllog_items=calllog_item;
list.addOnItemTouchListener(new RecyclerItemClickListener(c, list ,new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Button call= (Button) view.findViewById(R.id.call_txt);
Button block= (Button) view.findViewById(R.id.block_txt);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c, "call", Toast.LENGTH_SHORT).show();
}
});
block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(c, "blockbbb222", Toast.LENGTH_SHORT).show();
}
});
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
expandedPosition = position;
notifyItemChanged(expandedPosition);
}
#Override
public void onLongItemClick(View view, int position) {
// do whatever
}
}));
}
#Override
public void onBindViewHolder(RecordHolder holder, int position) {
calllog_item list=calllog_items.get(position);
holder.contact_name.setText(list.getContact_name());
holder.contact_img.setImageBitmap(list.getContact_img());
holder.call_type.setImageBitmap(list.getCall_type());
holder.call_duration.setText(list.getCall_duration());
holder.call_timing.setText(list.call_timing);
holder.contact_no.setText(list.getCall_no());
if (position == expandedPosition) {
holder.llExpandArea.setVisibility(View.VISIBLE);
} else {
holder.llExpandArea.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return calllog_items.size();
}
public class RecordHolder extends RecyclerView.ViewHolder {
TextView contact_name,call_timing,call_duration,contact_no;
ImageView contact_img,call_type;
LinearLayout llExpandArea;
public RecordHolder(View itemView) {
super(itemView);
contact_img= (ImageView) itemView.findViewById(R.id.calllog_contact_img);
call_type= (ImageView) itemView.findViewById(R.id.calllog_call_type);
call_duration= (TextView) itemView.findViewById(R.id.calllog_call_duration);
call_timing= (TextView) itemView.findViewById(R.id.calllog_call_timing);
contact_name= (TextView) itemView.findViewById(R.id.calllog_contact_name);
contact_no= (TextView) itemView.findViewById(R.id.calllog_no);
llExpandArea=(LinearLayout)itemView.findViewById(R.id.llExpandArea);
}
}
}
Did you try to set it as clicable and focusable?
XML
android:focusable="true"
android:clickable="true"
Java
button.setClickable("true");
button.setFocusable("true");
If nothing changes, try to put a log call in your onClick method (maybe there's something bad in the code), or in OnTouch.
I have created RecyclerView. When it renders on screen it shows only one item per screen. I can see next item when I scroll down RecyclerView. Here is my code
public class LeaveStatusViewAdapter extends RecyclerView
.Adapter<LeaveStatusViewAdapter
.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Employee> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView startDate;
TextView endDate;
TextView leaveType;
TextView leaveDays;
TextView leaveReason;
TextView leaveStatus;
public DataObjectHolder(View itemView) {
super(itemView);
startDate = (TextView) itemView.findViewById(R.id.textView_StartDate);
endDate = (TextView) itemView.findViewById(R.id.textView_EndDate);
leaveType = (TextView) itemView.findViewById(R.id.textView_LeaveType);
leaveDays = (TextView) itemView.findViewById(R.id.textView_LeaveDays);
leaveReason = (TextView) itemView.findViewById(R.id.textView_LeaveReason);
leaveStatus = (TextView) itemView.findViewById(R.id.textView_LeaveStatus);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public LeaveStatusViewAdapter(ArrayList<Employee> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.startDate.setText(mDataset.get(position).getLeaveStartDate());
holder.endDate.setText(mDataset.get(position).getLeavesEndDate());
holder.leaveType.setText(mDataset.get(position).getLeaveType());
holder.leaveDays.setText(mDataset.get(position).getLeaveDays());
holder.leaveReason.setText(mDataset.get(position).getLeaveReason());
holder.leaveStatus.setText(mDataset.get(position).getLeaveStatus());
}
public void addItem(Employee dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
Following is activity class
public class LeaveStatusActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leave_status);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new LeaveStatusViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
((LeaveStatusViewAdapter) mAdapter).setOnItemClickListener(new LeaveStatusViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private ArrayList<Employee> getDataSet() {
ArrayList results = new ArrayList<Employee>();
for (int index = 0; index < 3; index++) {
Employee obj = new Employee(" : 15/07/2016",
" : 20/07/2016"," : EL: Earned Leave"," : 5"," : Not feeeling well"," : Pending");
results.add(index, obj);
}
return results;
}
}
Following is Layout files
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.leave.mcgm.mcgmleavemanagement.LeaveStatusActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
</LinearLayout>
Following custom view for each item in RecyclerView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/lbl_StartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:text="Start Date"/>
<TextView
android:id="#+id/textView_StartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/lbl_StartDate" />
<TextView
android:id="#+id/lbl_EndDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Date"
android:textStyle="bold"
android:layout_marginStart="24dp"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/textView_LeaveReason" />
<TextView
android:id="#+id/textView_EndDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/lbl_EndDate"
android:layout_alignBottom="#+id/lbl_EndDate"
android:layout_toEndOf="#+id/lbl_EndDate" />
<TextView
android:id="#+id/lbl_LeaveType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="LeaveType"
android:layout_below="#+id/lbl_EndDate"
android:layout_alignParentStart="true"
android:textStyle="bold"/>
<TextView
android:id="#+id/textView_LeaveType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text=""
android:layout_alignBaseline="#+id/lbl_LeaveType"
android:layout_alignBottom="#+id/lbl_LeaveType"
android:layout_toEndOf="#+id/lbl_LeaveType" />
<TextView
android:id="#+id/lbl_LeaveDays"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leave Days"
android:singleLine="true"
android:layout_below="#+id/lbl_EndDate"
android:layout_alignStart="#+id/lbl_EndDate"
android:textStyle="bold"/>
<TextView
android:id="#+id/textView_LeaveDays"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text=""
android:layout_alignBaseline="#+id/lbl_LeaveDays"
android:layout_alignBottom="#+id/lbl_LeaveDays"
android:layout_toEndOf="#+id/lbl_LeaveDays" />
<TextView
android:id="#+id/lbl_LeaveReason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leave Reason"
android:singleLine="true"
android:layout_alignTop="#+id/textView_LeaveReason"
android:layout_alignParentStart="true"
android:textStyle="bold"/>
<TextView
android:id="#+id/textView_LeaveReason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text=""
android:layout_below="#+id/textView_LeaveDays"
android:layout_toEndOf="#+id/lbl_LeaveReason" />
<TextView
android:id="#+id/lbl_LeaveStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Leave Status"
android:singleLine="true"
android:layout_alignBaseline="#+id/textView_LeaveStatus"
android:layout_alignBottom="#+id/textView_LeaveStatus"
android:layout_alignParentStart="true"
android:textStyle="bold"/>
<TextView
android:id="#+id/textView_LeaveStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text=""
android:layout_below="#+id/lbl_LeaveReason"
android:layout_toEndOf="#+id/lbl_LeaveReason"
android:textAllCaps="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Am I missing something here??
You should change the view of each element of the list to android:layout_height="wrap_content"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
.....
</LinearLayout>
When you use android:layout_height="match_parent" every item of the list will try to use the maximum space possible in the screen