Child RecyclerView inside Parent RecyclerView is showing at End of Parent RecyclerView ?
I Want To Show Categroy in Parent RecyclerView & show its Sub Category in Child RecyclerView
But When I Click Parent RecyclerView To Show That Sub Category the Child RecyclerView is showing at The Full End Of Parent Category Please Check Where Is I'm Wrong?
Here is My Results:
First Item Clicked
.
Second Item Clicked
My Code:
This Is My Main Layout:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".USER.Category">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Category"/>
</LinearLayout>
This is my Main java File:
public class Category extends AppCompatActivity {
static Toast Toasts;
RecyclerView Category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
Category = findViewById(R.id.Category);
Category.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
Category_View_request();
}
public void Category_View_request() {
RequestQueue requestQueue = Volley.newRequestQueue(Category.this);
String url = Constant.Category;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GridView_listItems[] Category_View_response = gson.fromJson(response, GridView_listItems[].class);
Category.setAdapter(new CategoryView_Adapter(Category.this, Category_View_response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toasts = Toast.makeText(Category.this, "ERROR: Please Check Internet & Try Again", Toast.LENGTH_SHORT);
Toasts.show();
}
});
requestQueue.add(stringRequest);
}
}
this is Parent Layout:
<?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="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="5dp"
android:id="#+id/layout">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:id="#+id/nameLayout">
<ImageView
android:id="#+id/categoryimage"
android:layout_width="120dp"
android:layout_height="120dp"
android:adjustViewBounds="true"
android:background="#fff"
android:contentDescription="#string/todo"
android:padding="8dp"
android:scaleType="fitXY" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:paddingRight="8dp"
android:paddingBottom="8dp">
<Space
android:layout_width="112dp"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:paddingRight="8dp"
android:paddingBottom="8dp">
<TextView
android:id="#+id/categoryname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="1dp"
android:singleLine="true"
android:text="#string/test_product_name"
android:textColor="#color/Black"
android:textSize="13sp"
tools:ignore="RtlSymmetry" />
<TextView
android:id="#+id/categorydec"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="1dp"
android:paddingTop="3dp"
android:singleLine="true"
android:text="#string/test_product_description"
android:textColor="#color/common_google_signin_btn_text_light_default"
android:textSize="12sp"
tools:ignore="RtlSymmetry" />
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/click">
</RelativeLayout>
</RelativeLayout>
<androidx.cardview.widget.CardView
android:id="#+id/subview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#color/White"
android:elevation="8dp"
android:paddingTop="10dp"
>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/subCatview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
This is Parent Adapter:
public class CategoryView_Adapter extends RecyclerView.Adapter<CategoryView_Adapter.CategoryViewHolder> {
Toast Toasts;
private static Context context;
private static GridView_listItems[] data;
public CategoryView_Adapter(Context context, GridView_listItems[] data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public CategoryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.category_view, parent, false);
return new CategoryViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final CategoryViewHolder holder, int position) {
final GridView_listItems CategoryList = data[position];
holder.categoryname.setText(CategoryList.getName());
holder.categorydec.setText(CategoryList.getId());
Glide.with(holder.categoryimage.getContext())
.applyDefaultRequestOptions(new RequestOptions()
.placeholder(R.drawable.product_loading)
.error(R.drawable.product_loading_failed))
.load(Constant.MAINImagUrl + CategoryList.getCategoryLogo().substring(2))
.into(holder.categoryimage);
holder.categoryname.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.layout.setBackgroundColor(ContextCompat.getColor(context, R.color.common_google_signin_btn_text_light_default));
Grid_View_request(CategoryList.getName());
}
});
}
#Override
public int getItemCount() {
return data.length;
}
public static class CategoryViewHolder extends RecyclerView.ViewHolder {
ImageView categoryimage;
TextView categoryname, categorydec;
CardView subview;
RelativeLayout click;
LinearLayout layout;
public static RecyclerView subCatview;
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
categoryimage = (ImageView) itemView.findViewById(R.id.categoryimage);
categoryname = (TextView) itemView.findViewById(R.id.categoryname);
categorydec = (TextView) itemView.findViewById(R.id.categorydec);
click = (RelativeLayout) itemView.findViewById(R.id.click);
subview = (CardView) itemView.findViewById(R.id.subview);
layout = (LinearLayout) itemView.findViewById(R.id.layout);
subCatview = (RecyclerView) itemView.findViewById(R.id.subCatview);
GridLayoutManager gridLayoutManager = new GridLayoutManager(MyApplication.getAppContext(), 3, GridLayoutManager.VERTICAL, false);
subCatview.setLayoutManager(gridLayoutManager);
}
}
public static void Grid_View_request(final String category) {
RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
String url = Constant.Sub_Category;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.contains("CityGroceryEmptyResponse")) {
Toast.makeText(MyApplication.getAppContext(), "No Sub Category Found", Toast.LENGTH_SHORT).show();
} else {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Sub_Category_list[] Sub_Category_list = gson.fromJson(response, Sub_Category_list[].class);
subCatview.setAdapter(new Sub_Category_Adapter(MyApplication.getAppContext(), Sub_Category_list));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyApplication.getAppContext(), "ERROR: Please Check Internet & Try Again", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("category", category);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
}
This is My Child Layout:
<androidx.cardview.widget.CardView 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="120dp"
android:layout_gravity="center"
android:layout_margin="2dp"
android:orientation="horizontal"
android:elevation="8dp"
app:cardCornerRadius="1dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:paddingRight="8dp"
android:paddingBottom="8dp">
<ImageView
android:id="#+id/subCatNameimage"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/subCatName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/subCatNameimage"
android:layout_marginTop="4dp"
android:gravity="center"
android:maxLength="30"
android:text="menu name"
android:textColor="#color/colorPrimary"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/subCatNameimage" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
This is My Child Adapter:
public class Sub_Category_Adapter extends RecyclerView.Adapter<Sub_Category_Adapter.CategoryViewHolder> {
Toast Toasts;
private static Context context;
private static Sub_Category_list[] data;
public Sub_Category_Adapter(Context context, Sub_Category_list[] data) {
this.context = context;
this.data = data;
final Sub_Category_list SubCategoryList = data[0];
}
#NonNull
#Override
public CategoryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.gridview_items, parent, false);
return new CategoryViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CategoryViewHolder holder, final int position) {
final Sub_Category_list SubCategoryList = data[position];
holder.subCatName.setText(SubCategoryList.getSubCategoryName());
Glide.with(holder.subCatNameimage.getContext())
.applyDefaultRequestOptions(new RequestOptions()
.placeholder(R.drawable.product_loading)
.error(R.drawable.product_loading_failed))
.load(Constant.MAINImagUrl + SubCategoryList.getSubCategoryLogo().substring(2))
.into(holder.subCatNameimage);
}
#Override
public int getItemCount() {
return data.length;
}
public static class CategoryViewHolder extends RecyclerView.ViewHolder {
ImageView subCatNameimage;
TextView subCatName;
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
subCatName = (TextView) itemView.findViewById(R.id.subCatName);
subCatNameimage = (ImageView) itemView.findViewById(R.id.subCatNameimage);
}
}
}
Please Correct Me Where is doing Mistake
Thanks In Advance
You can achieve that requirement by using an expandable recycler view.
There are a lot of libraries you can use to achieve this.
You can use this library.
Or follow this post to achieve this on your own, you might need to make some changes to get the output as per your requirement.
I'am achieve My requirement by using an expandable recycler view
HERE
Related
I tried the solutions on the other similar posts that I found here but they did not help me. I hope someone can help.
I get data from Unsplash's API and the ArrayList contains 10 items once I get a response, that's why I think It has to be something with the way the view is inflated.
This is code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "unsplash";
private final String CLIENT_ID = "...myclientID...";
// testing keyword used on the API to search for pictures
private final String KEYWORD = "stackOverflow";
private final String urlBase = "https://api.unsplash.com/";
private Retrofit retrofit;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl(urlBase)
.addConverterFactory(GsonConverterFactory.create())
.build();
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter = new RecyclerViewAdapter();
recyclerView.setAdapter(recyclerViewAdapter);
getData();
}
private void getData() {
PictureService service = retrofit.create(PictureService.class);
Call<PictureResponse> pictureResponseCall = service.getPictureList(KEYWORD, CLIENT_ID);
pictureResponseCall.enqueue(new Callback<PictureResponse>() {
#Override
public void onResponse(Call<PictureResponse> call, Response<PictureResponse> response) {
if (response.isSuccessful()){
PictureResponse pictureResponse = response.body();
ArrayList<UnsplashPic> pictureList = pictureResponse.getResults();
recyclerViewAdapter.addPictures(pictureList);
}else{
Log.e (TAG, " onResponse " + response.errorBody());
}
}
#Override
public void onFailure(Call<PictureResponse> call, Throwable t) {
Log.e (TAG, " onFailure " + t.getMessage());
}
});
}
}
My adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UnsplashPic> pictureList;
public RecyclerViewAdapter (){
pictureList = new ArrayList<>();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view_holder, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
UnsplashPic pic = pictureList.get(i);
viewHolder.artistName.setText(pic.user.getUsername());
viewHolder.unsplash.setText("Unsplash");
}
#Override
public int getItemCount() {
return pictureList.size();
}
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView artistName;
private TextView unsplash;
public ViewHolder (View itemView){
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
artistName = itemView.findViewById(R.id.artist_name);
unsplash = itemView.findViewById(R.id.unsplash_name);
}
}
}
item_view_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#ababab"
android:contentDescription="unsplash picture" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Photo by "/>
<TextView
android:id="#+id/artist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="on "/>
<TextView
android:id="#+id/unsplash_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
activity_main.xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search for pictures"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
you are actually adding the content of the pictureList you send as parameter of the function to that same list, your list from adapter is not updated.
You should do like this instead:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
this.pictureList.addAll(pictureList);
notifyDataSetChanged();
}
I tried below code to implement an expend and collapse content using recyclerview(listview) a link
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
if (isExpanded)
previousExpandedPosition = position;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1:position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
In my case when i click the particular position in recyclerview its expanding but it goes above the recyclerview.I cant see the full expanded content.i can see only partial content.In this case i need to scroll the recyclerview to view the full content.But i am searching for a solution to view the content without scroll the recyclerview. If i click another position in recyclerview that should be placed over an recyclerview.
Hear is My Code
public class CommonFragment extends Fragment {
#BindView(R.id.news_lists)
RecyclerView news_lists;
#BindView(R.id.nested_scroll)
NestedScrollView nested_scroll;
ArrayList<String> Names;
ArrayList<String> responseProducts = null;
NewsListAdaspters mAdapter;
Context mContext;
String position_name;
public CommonFragment() {
}
public static CommonFragment getInstance(String position, ArrayList<String> response) {
CommonFragment fragmentDummy = new CommonFragment();
Bundle args = new Bundle();
args.putStringArrayList("Types", response);
args.putString("position", position);
fragmentDummy.setArguments(args);
return fragmentDummy;
}
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.responseProducts = args.getStringArrayList("Types");
this.position_name = args.getString("position");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.fragment_common, container, false);
ButterKnife.bind(this, view);
} catch (InflateException ignored) {
}
mContext = getActivity();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
news_lists.setLayoutManager(mLayoutManager);
news_lists.setNestedScrollingEnabled(false);
Names = new ArrayList<>();
Names.clear();
for (int i = 0; i < 15; i++) {
Names.add("News Details " + i);
}
Log.e("position_name==>", "" + position_name);
getList();
return view;
}
private void getList() {
if (responseProducts.size() > 0) {
mAdapter = new NewsListAdaspters(mContext, responseProducts, position_name);
news_lists.setAdapter(mAdapter);
}
}
public class NewsListAdaspters extends RecyclerView.Adapter<NewsListAdaspters.MyViewHolder> {
private ArrayList<String> data;
private Context context;
private String name;
int mExpandedPosition = -1;
int previousExpandedPosition = -1;
NewsListAdaspters(Context context, ArrayList<String> maps, String selectedFragmentName) {
this.context = context;
this.data = maps;
this.name = selectedFragmentName;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.common_view, parent, false);
final MyViewHolder holder = new MyViewHolder(itemView);
return holder;
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
holder.news_description.setText(data.get(position));
holder.news_title.setText(name);
final boolean isExpanded = position == mExpandedPosition;
Log.e("isExpanded=====>", "" + isExpanded);
holder.expend_layout.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
holder.itemView.setActivated(isExpanded);
if (isExpanded)
previousExpandedPosition = position;
holder.news_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Activity_NewsFullDetails.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
holder.expand_click_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1 : position;
notifyItemChanged(previousExpandedPosition);
notifyItemChanged(position);
}
});
holder.share_fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "WORKING!!!!", Toast.LENGTH_SHORT).show();
}
});
holder.share_whatsapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "WORKING!!!!", Toast.LENGTH_SHORT).show();
}
});
holder.share_twet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "WORKING!!!!", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.news_title)
public TextView news_title;
#BindView(R.id.news_hour)
public TextView news_hour;
#BindView(R.id.news_description)
public TextView news_description;
#BindView(R.id.news_image)
public ImageView news_image;
#BindView(R.id.expand_click_layout)
RelativeLayout expand_click_layout;
#BindView(R.id.expend_layout)
public LinearLayout expend_layout;
#BindView(R.id.full_title)
public TextView full_title;
#BindView(R.id.txt_description)
public TextView txt_description;
#BindView(R.id.share_twet)
public ImageView share_twet;
#BindView(R.id.share_whatsapp)
public ImageView share_whatsapp;
#BindView(R.id.share_fb)
public ImageView share_fb;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#03000000">
<android.support.v4.widget.NestedScrollView
android:id="#+id/nested_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:fitsSystemWindows="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollbars="none">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
<android.support.v7.widget.RecyclerView
android:id="#+id/news_lists"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
ITEM XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:animateLayoutChanges="true"
android:background="#drawable/comment_background"
android:stateListAnimator="#animator/comment_selection"
android:elevation="3dp"
card_view:cardCornerRadius="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/news_image"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_margin="2dp"
android:background="#drawable/icon_card"
android:scaleType="fitXY" />
<RelativeLayout
android:id="#+id/expand_click_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/news_image"
android:layout_alignTop="#+id/news_image"
android:layout_toEndOf="#+id/news_image"
android:layout_toRightOf="#+id/news_image">
<TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_layout"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:maxEms="3"
android:maxLines="4"
android:padding="4dp"
android:text=""
android:textColor="#color/black_color"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_margin="4dp">
<TextView
android:id="#+id/news_hour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/center_text"
android:layout_toStartOf="#+id/center_text"
android:maxLines="2"
android:text="Hours"
android:textColor="#color/black_color"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/center_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/center_text"
android:layout_toRightOf="#+id/center_text"
android:gravity="end"
android:text="News Title"
android:textColor="#color/black_color"
android:textSize="16sp" />
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/expend_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/news_image"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="#+id/full_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Title Text"
android:textColor="#color/black_color"
android:textSize="20sp" />
<TextView
android:id="#+id/txt_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/large_text1"
android:textColor="#color/black_color"
android:textSize="18sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:orientation="horizontal">
<ImageView
android:id="#+id/share_fb"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/share_facebook" />
<ImageView
android:id="#+id/share_whatsapp"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/share_whatsapp" />
<ImageView
android:id="#+id/share_twet"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/share_tweet" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Try to use NestedScrollView instead of ScrollView and set below to your activity :-
recyclerView.setNestedScrollingEnabled(false);
For more information you can refer below stackoverflow links:-
How to use RecyclerView inside NestedScrollView?
Recyclerview inside ScrollView not scrolling smoothly
I'm trying to adapt a recyclerview to display a list of objects. But actually I have some kind of wierd bug. My object have ID and Name data to display, but in the list, at first, I only can see the Id, and when I scroll down, only the rows going completely out of the screen are completely displayed...
This is my ListPresentActivity.
public class ListPresentActivity extends AppCompatActivity implements ViewInterface {
private static final String EXTRA_PRESENT_ID = "EXTRA_PRESENT_ID";
private static final String EXTRA_PRESENT_NAME = "EXTRA_PRESENT_NAME";
private List<PresentItem> listOfPresent;
private LayoutInflater layoutInflater;
private RecyclerView recyclerView;
private CustomAdapter adapter;
private PresentController presentController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_present);
recyclerView = (RecyclerView) findViewById(R.id.rec_list_activity);
recyclerView.setHasFixedSize(true);
layoutInflater = getLayoutInflater();
presentController = new PresentController(this, new FakePresentModel());
}
#Override
public void startDetailActivity(int id, String name, String info, String target, String advice, String price) {
//public void startDetailActivity(int id) {
Intent i = new Intent(this,PresentDetailActivity.class);
i.putExtra(EXTRA_PRESENT_ID, id);
i.putExtra(EXTRA_PRESENT_NAME, name);
startActivity(i);
}
#Override
public void setUpAdapterAndView(List<PresentItem> listOfPresent) {
this.listOfPresent = listOfPresent;
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);
}
private class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder>{
#Override
public CustomAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = layoutInflater.inflate(R.layout.item_present, parent, false);
return new CustomViewHolder(v);
}
#Override
public void onBindViewHolder(CustomAdapter.CustomViewHolder holder, int position) {
PresentItem currentPresent = listOfPresent.get(position);
holder.id.setText(
Integer.toString(currentPresent.getId())
);
holder.name.setText(
currentPresent.getName()
);
}
#Override
public int getItemCount() {
return listOfPresent.size();
}
class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView id;
private TextView name;
private ViewGroup container;
public CustomViewHolder(View itemView){
super(itemView);
this.id = (TextView) itemView.findViewById(R.id.texv_item_id);
this.name = (TextView) itemView.findViewById(R.id.texv_item_name);
this.container = (ViewGroup) itemView.findViewById(R.id.root_list_present);
this.container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
PresentItem presentItem = listOfPresent.get(
this.getAdapterPosition()
);
presentController.onListItemClick(presentItem);
}
}
}
}
The layout item_present.xml
<android.support.constraint.ConstraintLayout 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="88dp"
android:id="#+id/root_list_present"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/texv_item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:textSize="48sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="#id" />
<TextView
android:id="#+id/texv_item_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="84dp"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:maxLines="1"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="collier" />
</android.support.constraint.ConstraintLayout>
And my list layout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.lubbee.bruh.view.ListPresentActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rec_list_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
I have search for a long time now, and the only concording result I have fount seems to be fixed with the recyclerView.setHasFixedSize(true); which is not my case...
Thanks for your time!
PS : If there is some code parts needed missing, just say the word! :]
Just after the first loading.
After one scroll to the bottom and back to the top of the screen
<LinearLayout android:layout_width="match_parent"
android:layout_height="88dp"
android:weightSum="1"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_gravity="center_vertical"
android:layout_weight="0.2"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center_vertical"
android:layout_weight="0.8"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
Try this simple LinearLayout it should work
You can also add other properties, but for now try it out
I am developing a chat application. The chat messages consists of normal text messages and sometimes it can be a list of items in a recyclerview.
So I've implemented nested Recyclerview. So what happens is in the json response if the message is just a normal text is a textview will be displayed but the message contains a URL then the horizantal recyclerview is shown in place of textview.
The problem is if in the json reponse let's say there are 10 messages and in that 10, 4 of them are URL's so i should be seeing 6 normal texts and 4 Recyclerviews. But the nested recyclerview is behaving very oddly sometimes it doesn't even display, sometimes i can see 2 Recyclerviews and sometimes 4 of them but with the same URL (same list of items).
I don't what i am doing wrong. can someone take a look at the code and tell me what's wrong?
My Parent(Vertical) Recyclerview layout
<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">
<data>
<variable
name="messageViewModel"
type="com.sukshi.sukshichat.viewmodel.MessageFragmViewModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.fragment.MessagesFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#ffffff"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:layout_marginTop="0dp"
android:layout_below="#+id/kjk"
android:layout_above="#+id/rv_message_container"
tools:listitem="#layout/test"
/>
</RelativeLayout>
</layout>
Vertical Recyclerview child layout
<?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">
<data>
<import
alias="cons"
type="com.sukshi.sukshichat.utils.ConstantsFirebase"/>
<import type="android.view.View"/>
<variable
name="messageViewModel"
type="com.sukshi.sukshichat.viewmodel.MessageAdapterViewModel"/>
</data>
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:id="#+id/rv_container"
android:layout_width="wrap_content">
<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:id="#+id/nested_recyclerview"
>
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:id="#+id/sender"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="4dp"
app:layout_widthPercent="70%">
<hani.momanii.supernova_emoji_library.Helper.EmojiconTextView
android:layout_height="wrap_content"
android:id="#+id/tv_item_message"
android:layout_width="wrap_content"
android:maxWidth="300dp"
android:textColor="#ffffff"
android:text="#{messageViewModel.message}"
android:background="#drawable/chat_sender"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{messageViewModel.time}"
android:layout_marginRight="4dp"
android:id="#+id/tv_item_message_time"
android:layout_alignBottom="#+id/tv_item_message"
android:layout_toLeftOf="#+id/tv_item_message"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="#dimen/item_message_max_height"
android:maxWidth="#dimen/item_message_max_width"
android:onClick="#{messageViewModel::onItemClick}"
android:scaleType="centerCrop"
android:transitionName="shared"
android:visibility="#{messageViewModel.typeMessage ? View.GONE : View.VISIBLE}"
app:mapLocation="#{messageViewModel.mapLocation}"
app:photoUrlMessage="#{messageViewModel.message}"/>
</FrameLayout>
</RelativeLayout>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:id="#+id/reciever"
android:layout_marginBottom="4dp"
app:layout_widthPercent="70%">
<hani.momanii.supernova_emoji_library.Helper.EmojiconTextView
android:layout_height="wrap_content"
android:id="#+id/tv_item_message1"
android:layout_width="wrap_content"
android:background="#drawable/chat_recieve"
android:maxWidth="300dp"
android:textColor="#000000"
android:text="#{messageViewModel.message}"
android:padding="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/show_garments2"
android:text="Show Garments"
android:visibility="gone"
android:background="#drawable/chat_recieve"
android:elevation="10dp"
android:paddingLeft="10dp"
android:textColor="#000000"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{messageViewModel.time}"
android:id="#+id/tv_item_message_time11"
android:layout_marginLeft="4dp"
android:layout_alignBottom="#+id/tv_item_message1"
android:layout_toRightOf="#+id/tv_item_message1"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iv_image1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="#dimen/item_message_max_height"
android:maxWidth="#dimen/item_message_max_width"
android:onClick="#{messageViewModel::onItemClick}"
android:scaleType="centerCrop"
android:transitionName="shared"
android:visibility="#{messageViewModel.typeMessage ? View.GONE : View.VISIBLE}"
app:mapLocation="#{messageViewModel.mapLocation}"
app:photoUrlMessage="#{messageViewModel.message}"/>
</FrameLayout>
</RelativeLayout>
</android.support.percent.PercentRelativeLayout>
</layout>
Vertical Recyclerview adapter
private void initializeFirebase() {
if (valueUserListener == null) {
valueUserListener = createFirebaseUsersListeners();
}
mRefUsers = FirebaseDatabase.getInstance().getReference(ConstantsFirebase.FIREBASE_LOCATION_USERS);
mRefUsers.keepSynced(true);
mRefUsers.addValueEventListener(valueUserListener);
Query messagesRef = FirebaseDatabase.getInstance()
.getReference(ConstantsFirebase.FIREBASE_LOCATION_CHAT)
.child(mChildChatKey)
.orderByKey().limitToLast(50);
messagesRef.keepSynced(true);
attachMessagesToRecyclerView(messagesRef);
}
private void attachMessagesToRecyclerView(final Query messagesReference) {
mAdapter = new FirebaseRecyclerAdapter<Message, MessageItemHolder>(Message.class,
R.layout.test123, MessageItemHolder.class, messagesReference) {
#Override
public MessageItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Test123Binding adapterItemMessageBinding = DataBindingUtil.inflate(LayoutInflater
.from(parent.getContext()), viewType, parent, false);
return new MessageItemHolder(adapterItemMessageBinding);
}
#Override
protected void populateViewHolder(final MessageItemHolder viewHolder, final Message message, int position) {
int index = mUsersEmails.indexOf(message.getEmail());
if (index != -1) {
viewHolder.bindMessage(mUsers.get(index), message, MessagesFragment.this);
}
if (viewHolder.mAdapterItemMessageBinding.getMessageViewModel().isSender()){
viewHolder.mAdapterItemMessageBinding.reciever.setVisibility(View.GONE);
viewHolder.mAdapterItemMessageBinding.sender.setVisibility(View.VISIBLE);
}else {
viewHolder.mAdapterItemMessageBinding.reciever.setVisibility(View.VISIBLE);
viewHolder.mAdapterItemMessageBinding.sender.setVisibility(View.GONE);
}
String http = message.getMessage();
// if (htttpmessage != null){
if (http.contains("google") && message.getType() == 0){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutParams(params);
filterLink = message.getMessage();
ListOfdataAdapter.clear();
JSON_HTTP_CALL(filterLink);
nestedRecyclerview(viewHolder);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setVisibility(View.VISIBLE);
viewHolder.mAdapterItemMessageBinding.tvItemMessage1.setVisibility(View.INVISIBLE);
// filterLink = message.getFilterLink();
}else{
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(0,
0);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutParams(params);
viewHolder.bindMessage(mUsers.get(index), message, MessagesFragment.this);
viewHolder.mAdapterItemMessageBinding.tvItemMessage1.setVisibility(View.VISIBLE);
}
if (message.getType() == 1 || message.getType() == 2){
viewHolder.mAdapterItemMessageBinding.tvItemMessage.setVisibility(View.INVISIBLE);
}else {
viewHolder.mAdapterItemMessageBinding.tvItemMessage.setVisibility(View.VISIBLE);
}
/* viewHolder.mAdapterItemMessageBinding.showGarments2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showpDialog();
filterLink = message.getMessage();
ListOfdataAdapter.clear();
JSON_HTTP_CALL(filterLink);
}
});
*/
}
};
mFragmentMessagesBinding.rvMessage.setAdapter(mAdapter);
mFragmentMessagesBinding.rvMessage.getAdapter().registerAdapterDataObserver(
new RecyclerView.AdapterDataObserver() {
#Override public void onItemRangeInserted(int position, int itemCount) {
super.onItemRangeInserted(position, itemCount);
mFragmentMessagesBinding.rvMessage.scrollToPosition(position);
}
});
}
So whenever there is a URl in the message key below method will be called
public void JSON_HTTP_CALL(String url){
RequestOfJSonArray = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
UploadImage GetDataAdapter2 = new UploadImage();
JSONObject json = null;
try {
hidepDialog();
json = array.getJSONObject(i);
GetDataAdapter2.setBrand_name(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImage(json.getString(Image_URL_JSON));
GetDataAdapter2.setGarment_price(json.getString(garment_price));
GetDataAdapter2.setGarment_name(json.getString(garment_name));
GetDataAdapter2.setImage_full(json.getString(image_full));
GetDataAdapter2.setDesc_text(json.getString(desc_text));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
// showFragment();
}
}
Horizantal Recyclerview adapter
final WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(WrapContentLinearLayoutManager.HORIZONTAL);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setLayoutManager(linearLayoutManager);
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setHasFixedSize(true);
//mFragmentMessagesBinding.recyclerview1.addItemDecoration(new PaddingItemDecoration(size));
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setItemAnimator(new DefaultItemAnimator());
DialogRecyclerViewAdapter rvAdapter = new DialogRecyclerViewAdapter(ListOfdataAdapter, getActivity());
viewHolder.mAdapterItemMessageBinding.nestedRecyclerview.setAdapter(rvAdapter);
rvAdapter.notifyDataSetChanged();
Horizantal Recyclerview Adapter
public class DialogRecyclerViewAdapter extends RecyclerView.Adapter<DialogRecyclerViewAdapter.ViewHolder> {
Context context;
List<UploadImage> dataAdapters;
private SharedPreferences.Editor mSharedPrefEditor;
ImageLoader imageLoader;
public DialogRecyclerViewAdapter(List<UploadImage> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
final UploadImage dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImage(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.drawable.loading_1,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView, garment_price, size;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
Vertical Recyclerview ViewHolder
public static class MessageItemHolder extends RecyclerView.ViewHolder {
private Test123Binding mAdapterItemMessageBinding;
public MessageItemHolder(Test123Binding adapterItemMessageBinding) {
super(adapterItemMessageBinding.rvContainer);
mAdapterItemMessageBinding = adapterItemMessageBinding;
}
public void bindMessage(User user, Message message, MessageAdapterViewModelContract contract) {
if (mAdapterItemMessageBinding.getMessageViewModel() == null) {
mAdapterItemMessageBinding.setMessageViewModel(new MessageAdapterViewModel(user,
encodedMail, message, contract));
} else {
mAdapterItemMessageBinding.getMessageViewModel().setUser(user);
mAdapterItemMessageBinding.getMessageViewModel().setMessage(message);
}
}
}
I have a recyclerview that contains the cardview.The data is coming from server and is populated in a list. The Cardview adapter is not inflating the 2nd value from the list. The activity shows only one value on the screen:
This is the cardview screen
Following is the code for Recycler view layout file:
<?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:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:scrollbars="vertical"
tools:context="com.appshaala.vorkal.app.ViewWorkerList">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Following is the code for worker_card layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:padding="16dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/WorkerCV"
app:cardBackgroundColor="#color/colorPrimaryDark"
android:elevation="5dp"
card_view:cardCornerRadius="#dimen/card_album_radius">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/pic"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="#drawable/cover"
android:contentDescription="Worker pic" />
</LinearLayout>
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Raja"
android:textSize="35sp"
android:foregroundGravity="center"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/Wrating"
android:layout_alignStart="#+id/Wrating"
android:textAlignment="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View Profile"
android:id="#+id/button2"
android:layout_below="#+id/thumbnail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/Wrating"
android:layout_toStartOf="#+id/Wrating" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call"
android:id="#+id/button3"
android:layout_alignTop="#+id/button2"
android:layout_alignRight="#+id/Wrating"
android:layout_alignEnd="#+id/Wrating" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Wrating"
style="?android:attr/ratingBarStyleIndicator"
android:foregroundGravity="center"
android:layout_below="#+id/Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:rating="3.5"
android:numStars="5" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Following is the code for worker adapter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.PersonViewHolder> {
private List<Worker> persons;
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
RatingBar personRating;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.WorkerCV);
personName = (TextView) itemView.findViewById(R.id.Name);
personRating = (RatingBar) itemView.findViewById(R.id.Wrating);
}
}
public WorkerAdapter(List<Worker> persons)
{
this.persons = persons;
Log.d("Size",""+persons.size());
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.worker_card, parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
Log.d("here","ya");
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
Log.d("Pos",""+position);
holder.personName.setText(persons.get(position).getName());
holder.personRating.setRating(persons.get(position).getRating());
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
Following is the code for ViewWorkerList that calls worker adapter and inflates the recycler view:
public class ViewWorkerList extends AppCompatActivity {
//Creating a List of workers
private List<Worker> listWorkers;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private WorkerAdapter adapter;
// Json nodes
private static String KEY_SUCCESS = "success";
private static String KEY_NAME = "name";
private static String KEY_PHONE = "phoneno";
String url = "http://vorkal.com/read_data.php";
ArrayList<HashMap<String, String>> Item_List;
public static final String KEY_SERVICE = "service";
private String service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(),"2nd page",Toast.LENGTH_LONG);
Log.d("2pg","2page");
Intent intent = getIntent();
service = intent.getStringExtra("service"); //if it's a string you stored.
setContentView(R.layout.worker_list_main);
//Initializing our workers list
listWorkers = new ArrayList<>();
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
StringRequest stringRequest = new StringRequest (Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("response",response.toString());
JSONObject jsonObject=new JSONObject(response);
int success = jsonObject.getInt("success");
//int success=response.getInt(KEY_SUCCESS);
// Log.d("response", response.getString("workers"));
Log.d("sucess",""+success);
String workerArray=jsonObject.getString("workers");
JSONArray jar=new JSONArray(workerArray);
JSONObject json = jar.getJSONObject(0);
Log.d("name",json.getString("name"));
parseData(jar);
} catch (Exception e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//recyclerView.setAdapter(new CardAdapter(listWorkers, this));
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Finally initializing our adapter
Log.d("listworkers",listWorkers.get(1).getName());
adapter = new WorkerAdapter(listWorkers);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Worker worker = new Worker();
JSONObject json = null;
try {
json = array.getJSONObject(i);
worker.setImageUrl(json.getString("pic"));
worker.setName(json.getString("name"));
worker.setLocation(json.getString("location"));
worker.setRating(json.getInt("rating"));
worker.setId(json.getInt("id"));
worker.setPhone(json.getInt("phonenumber"));
worker.setOccupation(json.getString("occupation"));
worker.setPrice(json.getInt("price"));
worker.setReview(json.getString("Review"));
} catch (JSONException e) {
e.printStackTrace();
}
listWorkers.add(worker);
}
}
}
The listWorkers contains 2 workers. But only one is getting populated in the cardview. The worker is the normal bean class. I am not able to see the 2nd worker card on the screen. Please help me out and suggest the changes.