How to switch layout when RecyclerView is List to Grid or vice versa.
build.gradle app level
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'de.hdodenhof:circleimageview:2.0.0'
ItemModel.java
public class ItemModel {
private String name;
private String imagePath;
public ItemModel(){
}
public ItemModel(String name, String imagePath) {
this.name = name;
this.imagePath = imagePath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
String imageUrl[] = Constant.image;
String names[] = Constant.name;
#BindView(R.id.my_recycler_view)
RecyclerView mRecyclerView;
private RecyclerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
}
private void initView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
List list = getList();
mAdapter = new RecyclerAdapter(this, list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
private List getList() {
List list = new ArrayList<>();
for (int i = 0; i < imageUrl.length; i++) {
ItemModel model = new ItemModel();
model.setName(names[i]);
model.setImagePath(imageUrl[i]);
list.add(model);
}
return list;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.switch_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
finish();
break;
case R.id.switch_view:
supportInvalidateOptionsMenu();
boolean isSwitched = mAdapter.toggleItemViewType();
mRecyclerView.setLayoutManager(isSwitched ? new LinearLayoutManager(this) : new GridLayoutManager(this, 2));
mAdapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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.sunil.switchlisttogridrecyclerview.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</RelativeLayout>
RecyclerAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by sunil on 12/10/16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter {
private List itemModels;
private Context context;
private static final int LIST_ITEM = 0;
private static final int GRID_ITEM = 1;
boolean isSwitchView = true;
public RecyclerAdapter(Context context, List itemModels) {
this.itemModels = itemModels;
this.context = context;
}
#Override
public int getItemCount() {
return itemModels.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView;
if (i == LIST_ITEM){
itemView = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.item_layout, null);
}else{
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view_grid, null);
}
return new ItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemModel model = itemModels.get(position);
initializeViews(model, holder, position);
}
#Override
public int getItemViewType (int position) {
if (isSwitchView){
return LIST_ITEM;
}else{
return GRID_ITEM;
}
}
public boolean toggleItemViewType () {
isSwitchView = !isSwitchView;
return isSwitchView;
}
private void initializeViews(ItemModel model, final RecyclerView.ViewHolder holder, int position) {
String imageUrl = model.getImagePath();
if (imageUrl != null && !imageUrl.isEmpty()){
Glide.with(context)
.load(imageUrl)
.into(((ItemViewHolder)holder).imageView);
}
((ItemViewHolder)holder).name.setText(model.getName());
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.name)
TextView name;
#BindView(R.id.imageView)
ImageView imageView;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_alignBaseline="#id/imageView"
android:layout_margin="10dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_toRightOf="#+id/imageView"/>
</RelativeLayout>
item_layout_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="0dp">
<RelativeLayout
android:padding="10dp"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_margin="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"/>
</RelativeLayout>
</RelativeLayout>
Related
i always mostly required Recycleview with viewbinding using interface in android java done any one help to do same ??
First of all put below code in build.Gradle(Module) in side android brackets
buildFeatures{
viewBinding true
}
Step 1 - Create recycler view in main activity xml layout
<?xml version="1.0" encoding="utf-8"?>
<!-- 1 -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
Step 2 - Create custom item layout xml By Right click on layout new -> layout Resource file
<?xml version="1.0" encoding="utf-8"?>
<!-- 2 -->
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_click"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="3dp"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="#+id/tv_logo"
android:src="#color/black"
android:padding="5dp"
android:layout_width="100dp"
android:layout_height="100dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/tv_title"
android:text="Amazon"
android:textSize="25sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RatingBar
android:id="#+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progressTint="#EFD80E"
android:rating="3"
style="#style/Widget.AppCompat.RatingBar.Indicator" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Step 3 - Create Item Class in java
package com.example.recyclerviewdemonewwithinterface.model;
// 3
public class Item {
private int id;
private String name;
private float rating;
private int image;
public Item(int id, String name, float rating, int image) {
this.id = id;
this.name = name;
this.rating = rating;
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
Step 4 - Create CustomItemAdapter Class in java
package com.example.recyclerviewdemonewwithinterface.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recyclerviewdemonewwithinterface.SetOnClickListener;
import com.example.recyclerviewdemonewwithinterface.databinding.CustomItemLayoutBinding;
import com.example.recyclerviewdemonewwithinterface.model.Item;
import java.util.List;
// 4
public class CustomItemAdapter extends RecyclerView.Adapter<CustomItemAdapter.MyViewHolder> {
CustomItemLayoutBinding binding;
private Context context;
private List<Item> itemList;
// i3 & create constructor also
private SetOnClickListener setOnClickListener;
public CustomItemAdapter(Context context, List<Item> itemList, SetOnClickListener setOnClickListener) {
this.context = context;
this.itemList = itemList;
this.setOnClickListener = setOnClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
binding = CustomItemLayoutBinding.inflate(LayoutInflater.from(context),parent,false);
MyViewHolder holder = new MyViewHolder(binding);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Item item = itemList.get(position);
holder.binding.tvLogo.setImageResource(item.getImage());
holder.binding.tvTitle.setText(item.getName());
holder.binding.ratingBar.setRating(item.getRating());
// i4
holder.binding.cardClick.setOnClickListener(view -> {
setOnClickListener.onItemClick(item,position);
});
// click event from adapter
/*holder.binding.cardClick.setOnClickListener(v -> {
Toast.makeText(context, ""+item.getName(), Toast.LENGTH_SHORT).show();
});*/
}
#Override
public int getItemCount() {
return itemList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
CustomItemLayoutBinding binding;
public MyViewHolder(#NonNull CustomItemLayoutBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
Step 5 - Create SetOnClickListener Interface in java
package com.example.recyclerviewdemonewwithinterface;
import com.example.recyclerviewdemonewwithinterface.model.Item;
// 6
public interface SetOnClickListener {
// i1
void onItemClick(Item item,int position);
void onLongItemClick(Item item, int position);
}
Step 6 - Apply Below code in Main Activity Java
package com.example.recyclerviewdemonewwithinterface;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.recyclerviewdemonewwithinterface.adapter.CustomItemAdapter;
import com.example.recyclerviewdemonewwithinterface.databinding.ActivityMainBinding;
import com.example.recyclerviewdemonewwithinterface.model.Item;
import java.util.ArrayList;
import java.util.List;
// i2 & implement methods
public class MainActivity extends AppCompatActivity implements SetOnClickListener {
// 5
ActivityMainBinding binding;
List<Item> itemList;
CustomItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
prepareData();
// i5 set interface in argument (Last this)
adapter = new CustomItemAdapter(MainActivity.this, itemList, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
// to show listview horizontaly
// LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false);
// to show grid view
// GridLayoutManager layoutManager = new GridLayoutManager(MainActivity.this,3);
// to show Straggered
// StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
// layout manager in recycle view
binding.recycleView.setLayoutManager(layoutManager);
binding.recycleView.setAdapter(adapter);
}
private void prepareData() {
itemList = new ArrayList<>();
itemList.add(new Item(1, "Instagram", 3.5f, R.drawable.ic_launcher_background));
itemList.add(new Item(2, "Pinterest", 2.5f, R.drawable.ic_launcher_background));
itemList.add(new Item(3, "YouTube", 3.f, R.drawable.ic_launcher_background));
itemList.add(new Item(4, "Twitter", 5.5f, R.drawable.ic_launcher_background));
itemList.add(new Item(5, "Whatsapp", 4.5f, R.drawable.ic_launcher_background));
}
#Override
public void onItemClick(Item item, int position) {
// i6
// Toast.makeText(this, ""+itemList.get(position).getName(), Toast.LENGTH_SHORT).show();
//
Toast.makeText(this, "" + item.getId()+"___"+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onLongItemClick(Item item, int position) {
}
}
I am unable to display the image (only) in RecyclerView stored in Firebase Storage, while I'm displaying the other text data in the recyclerView.
I browse through a lot of questions but i didn't find the answer for me .
hint: all roles for Realtime Database , Firebase Storage is set either to [true or test mode]
hint : below is the link for out put image :
https://i.stack.imgur.com/dagbA.jpg
data model
import com.google.firebase.database.Exclude;
public class House {
#Exclude
private String key;
//owner name
private String name ;
//location
private String Location;
//image
private String imageUrl;
/*all start with [RealState] (realTimeDatabase/storage)*/
/*
* [RealStateData] - database
* [RealStatePictures] - storage
* */
public House() {
//required
}
public House(String name, String location, String imageUrl) {
if (name.trim().equals("") || name.isEmpty()){
name = "realState company";
}
this.name = name;
Location = location;
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Exclude
public String getKey() {
return key;
}
#Exclude
public void setKey(String key) {
this.key = key;
}
}
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.techmarinar.royalhomes.data.House;
import java.util.List;
public class HouseAdapter extends RecyclerView.Adapter<HouseAdapter.HouseHolder> {
private static final String TAG = "HouseAdapter";
private Context mContext;
private List<House> houseList;
public HouseAdapter(Context mContext, List<House> houseList) {
this.mContext = mContext;
this.houseList = houseList;
}
public void setUploads(List<House> uploads) {
this.houseList = uploads;
this.notifyDataSetChanged();
}
#NonNull
#Override
public HouseHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(mContext)
.inflate(R.layout.list_item,parent,false);
return new HouseHolder(v);
}
#Override
public void onBindViewHolder(#NonNull HouseHolder holder, int position) {
//house object
House house = houseList.get(position);
holder.name.setText(house.getName());
holder.location.setText(house.getLocation());
// holder.image.setImageURI(Uri .parse(house.getImageUrl());
String imageUrl = house.getImageUrl();
Glide.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.centerCrop()
.into(holder.image);
}
#Override
public int getItemCount() {
return houseList.size();
}
#Override
public long getItemId(int position) {
return position;
}
public class HouseHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name;
private TextView location ;
public HouseHolder(#NonNull View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.xHouseImage);
name = (TextView) itemView.findViewById(R.id.xHouseName);
location = (TextView) itemView.findViewById(R.id.xHouseLocation);
}
}
}
MainActicity -- recyclerclass
package com.techmarinar.royalhomes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.techmarinar.royalhomes.data.House;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
//widget
private RecyclerView mRecycler;
private ProgressBar mProgress;
//firebase Element
private StorageReference storageReference;
private DatabaseReference databaseReference;
//Adapters var
private List<House> houseList;
private HouseAdapter mAdapter;
private ValueEventListener getFirebaseData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set Widget
setupUIWidget();
//init firebase
initiateFireBaseElement();
//set recyclerView
setupRecyclerView();
//get data from fire(storage/fireDataBase);
getHousesDataFromFireBase();
//setup Item Touch Helper
setupItemTouchHelper(mRecycler , mAdapter);
}
private void setupUIWidget() {
setTitle("home");
//widget
mProgress = (ProgressBar) findViewById(R.id.progress_circular);
mRecycler = (RecyclerView) findViewById(R.id.recycler);
FloatingActionButton mActionButton = (FloatingActionButton) findViewById(R.id.floatingBtn);
//ActionButton
mActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "wow", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this , EditHouse.class));
}
});
}
private void initiateFireBaseElement() {
//fireBase reference
databaseReference = FirebaseDatabase.getInstance().getReference("RealStateData");
storageReference= FirebaseStorage.getInstance().getReference("RealStatePictures") ;
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView: ");
houseList = new ArrayList<>();
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mRecycler.setHasFixedSize(true);
//mRecycler.setHasStableIds(true);
//init adapter
mAdapter = new HouseAdapter(MainActivity.this,houseList);
//set adapter to the recyclerView
mRecycler.setAdapter(mAdapter);
}
private void getHousesDataFromFireBase() {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
houseList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
//init house object
House houseValues = data.getValue(House.class);
// houseValues.setKey(data.getKey());
//fill the list
houseList.add(houseValues);
}
//notify the adapter
mAdapter.setUploads(houseList);
//mAdapter.notifyDataSetChanged();
//hide the progressBar
mProgress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, "onCancelled: " + error.getMessage());
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
//hide progressbar
mProgress.setVisibility(View.INVISIBLE);
}
});
}
private void setupItemTouchHelper(RecyclerView mRecycler, HouseAdapter mAdapter) {
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
}).attachToRecyclerView(mRecycler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu
MenuItem addNewHouse , deleteHouse , updateHouse;
addNewHouse= menu.add(0,1,1,"add house");
addNewHouse.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addNewHouse.setIcon(R.drawable.ic_baseline_supervised_user_circle_24);
updateHouse= menu.add(0,2,2,"update house");
deleteHouse= menu.add(0,3,3,"delete house");
addNewHouse.setOnMenuItemClickListener(this);
updateHouse.setOnMenuItemClickListener(this);
deleteHouse.setOnMenuItemClickListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case 1:
Toast.makeText(this, "new house", Toast.LENGTH_SHORT).show();
return true;
case 2:
Toast.makeText(this, "update house data", Toast.LENGTH_SHORT).show();
return true;
case 3:
Toast.makeText(this, "delete house data", Toast.LENGTH_SHORT).show();
return true;
default:return false;
}
}
}
here is xml files
List item:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp"
app:cardBackgroundColor="#color/purple_200"
app:cardElevation="12dp"
app:cardCornerRadius="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp">
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#color/purple_200"/>
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<ImageView
android:id="#+id/xHouseImage"
android:layout_width="match_parent"
android:layout_height="220dp"
android:adjustViewBounds="true" />
<!--this view is only for beautiful looks -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white"/>
<TextView
android:id="#+id/xHouseLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house Location"
android:layout_margin="4dp"
android:layout_marginStart="6dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="33sp"/>
<TextView
android:id="#+id/xHouseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="house owner name"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:fontFamily="sans-serif-light"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/black"
android:textSize="16sp"
android:gravity="top|center_vertical" />
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_goneMarginBottom="8dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="4dp"
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"
app:layout_constraintVertical_bias="0.029" />
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.446"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.406" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_home_work_24"
android:backgroundTint="#color/white"
android:foregroundGravity="bottom|right"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try this applyDefaultRequestOptions Method for Center crop of the image
Glide.with(mContext)
.applyDefaultRequestOptions(RequestOptions().centerCrop())
.load(imageUrl)
.placeholder(R.drawable.ic_baseline_add_business_24)
.into(target!!)
the problem was in Manifest.xml security issuess.
solution :
adding
android:usesCleartextTraffic="true"
to the application section
I want to retrieve information from my firebase database into a recyclerview which is in a fragment called fragment_schedule.xml, the layout of each entry is in blog_row.xml, The following is my code sample;
fragment_schedule.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ScheduleFragment"
android:orientation="vertical"
android:background="#drawable/blackboard2">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myrecycleView">
</android.support.v7.widget.RecyclerView>
blog_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
app:cardCornerRadius="12dp"
android:elevation="90dp"
android:layout_margin="7dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_date"
android:text="Date"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_time"
android:text="Time"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_event"
android:text="Event"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_moderator"
android:text="Moderator"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/post_venue"
android:text="Venue"/>
</LinearLayout>
</android.support.v7.widget.CardView>
ScheduleFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ScheduleFragment extends Fragment {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
public ScheduleFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Schedule,ScheduleViewHolder>firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Schedule, ScheduleViewHolder>
(Schedule.class,R.layout.blog_row,ScheduleViewHolder.class, mDatabase) {
#Override
protected void populateViewHolder(ScheduleViewHolder viewHolder, Schedule
model, int position) {
viewHolder.setEvent_name( model.getEvent_name() );
viewHolder.setEvent_date( model.getEvent_date() );
viewHolder.setEvent_moderator( model.getEvent_moderator() );
viewHolder.setEvent_time( model.getEvent_time() );
viewHolder.setEvent_venue( model.getEvent_venue() );
}
};
mBlogList.setAdapter( firebaseRecyclerAdapter );
}
public static class ScheduleViewHolder extends RecyclerView.ViewHolder{
View mView;
public ScheduleViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setEvent_name(String event_name){
TextView post_event = (TextView)mView.findViewById( R.id.post_event );
post_event.setText( event_name );
}
public void setEvent_moderator(String event_moderator){
TextView post_moderator = (TextView)mView.findViewById( R.id.post_moderator );
post_moderator.setText( event_moderator );
}
public void setEvent_time(String event_time){
TextView post_time = (TextView)mView.findViewById( R.id.post_time );
post_time.setText( event_time );
}
public void setEvent_venue(String event_venue){
TextView post_venue = (TextView)mView.findViewById( R.id.post_venue );
post_venue.setText( event_venue );
}
public void setEvent_date(String event_date) {
TextView post_date = (TextView)mView.findViewById( R.id.post_date );
post_date.setText( event_date );
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference().child("schedule");
mDatabase.keepSynced(true);
mBlogList = (RecyclerView) view.findViewById(R.id.myrecycleView);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
Schedule.java
public class Schedule {
private String event_name;
private String event_date;
private String event_moderator;
private String event_time;
private String event_venue;
public Schedule(String event_name, String event_date, String event_moderator, String
event_time, String event_venue) {
this.event_name = event_name;
this.event_date = event_date;
this.event_moderator = event_moderator;
this.event_time = event_time;
this.event_venue = event_venue;
}
public String getEvent_name() {
return event_name;
}
public void setEvent_name(String event_name) {
this.event_name = event_name;
}
public String getEvent_date() {
return event_date;
}
public void setEvent_date(String event_date) {
this.event_date = event_date;
}
public String getEvent_moderator() {
return event_moderator;
}
public void setEvent_moderator(String event_moderator) {
this.event_moderator = event_moderator;
}
public String getEvent_time() {
return event_time;
}
public void setEvent_time(String event_time) {
this.event_time = event_time;
}
public String getEvent_venue() {
return event_venue;
}
public void setEvent_venue(String event_venue) {
this.event_venue = event_venue;
}
public Schedule()
{
}
}
Everything seems fine and the application runs but the fragment is blank. I have gone over the code time and again and I can't find where I may have made a mistake. Please help
You are using an old version of FirebaseUI, you need to remove mBlogList.setHasFixedSize(true); so the data will appear in the page.
This was a bug in the older versions check here:
https://github.com/firebase/FirebaseUI-Android/issues/204
I'm new to android programming. I'm trying to make a single page app with a list of videos which I can scroll and do so, I am using RecyclerView. In my activity, it says a view cannot be converted to RecyclerView and as far as I know, RecyclerView does not have any widgets. What should I do? I will attach my code.
My activity:
package com.arvindsudheer.youtubeplayertesting;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* Created by ArvindSudheer on 6/10/2017.
*/
class RecyclerView {
public LinearLayoutManager layoutManager;
public MyAdapter adapter;
public boolean hasFixedSize;
private void setLayoutManager(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
private void setAdapter(MyAdapter adapter) {
this.adapter = adapter;
}
private void setHasFixedSize(boolean hasFixedSize) {
this.hasFixedSize = hasFixedSize;
}
/**
* Created by ArvindSudheer on 6/9/2017.
*/
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.childview1);
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
//to use RecycleView, you need a layout manager. default is
LinearLayoutManager
LinearLayoutManager linearLayoutManager=new
LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
MyAdapter adapter=new MyAdapter(MyActivity.this);
recyclerView.setAdapter(adapter);
}
}
}
MY Adapter:
package com.arvindsudheer.youtubeplayertesting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.VideoInfoHolder> {
//these ids are the unique id for each video
String[] VideoID = {"kN6lRqzmcOY", "MzmSFocMdJk", "L3LixkCN5tM","EuNaQCUjtCw","d-I2JSlEKtA","rwSf_12aMfE","13HIRNVFRlk","BH5_7IYvcVE","Lxc8-INx5G0","iwE8foegHkM","kCKUZdqo600","dr36AF4MqjY","IrMLXTw0528","gyxgVsXMYq0","71MTp2Ley3U","oeNRrGaGV20","loxMW2honqw","Sv63K3ESstA","7U8NzRAvy-I","2kdcR1QBqAI","n3w5c2VYcoU","2zA8W7h7ays","qfkbvujyPpc","JVF8pE1KxaA","f0bi0yl7uZU","5DbdWFAs8EI","5DbdWFAs8EI","2BFUvmCrn1o","yuYbVcoq9nk","lkFlQ5ECM8Q","JuYrl_49WA4","r3L87CUTxeU","RJMvq0pgvkg","9TuDEhfOLUc","HFTTDvuPMOs","fHRh1ksUOJg","OW7Gwuz8vTU","NitQnVpvzd4","-QOEEyuKPMY"};
Context ctx;
public MyAdapter(Context context) {
this.ctx = context;
}
#Override
public VideoInfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_view, parent, false);
return new VideoInfoHolder(itemView);
}
#Override
public void onBindViewHolder(final VideoInfoHolder holder, final int position) {
final YouTubeThumbnailLoader.OnThumbnailLoadedListener onThumbnailLoadedListener = new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailView.setVisibility(View.VISIBLE);
holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
}
};
holder.youTubeThumbnailView.initialize(Resource.KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(VideoID[position]);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(onThumbnailLoadedListener);
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
//write something for failure
}
});
}
#Override
public int getItemCount() {
return VideoID.length;
}
public class VideoInfoHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected RelativeLayout relativeLayoutOverYouTubeThumbnailView;
YouTubeThumbnailView youTubeThumbnailView;
protected ImageView playButton;
public VideoInfoHolder(View itemView) {
super(itemView);
playButton=(ImageView)itemView.findViewById(R.id.btnYoutube_player);
playButton.setOnClickListener(this);
relativeLayoutOverYouTubeThumbnailView = (RelativeLayout) itemView.findViewById(R.id.relativeLayout_over_youtube_thumbnail);
youTubeThumbnailView = (YouTubeThumbnailView) itemView.findViewById(R.id.youtube_thumbnail);
}
#Override
public void onClick(View v) {
Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) ctx, Resource.KEY, VideoID[getLayoutPosition()]);
ctx.startActivity(intent);
}
}
private class Resource {
public static final String KEY = "AIzaSyDOv0yWBimW8L8zIiYfTDYH9_9jFpZWgEw";
}
}
layout for each item :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent_relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="#drawable/image_ripple"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="0dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#android:color/black"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtube_thumbnail"
android:layout_width="match_parent"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:visibility="visible"/>
<RelativeLayout android:id="#+id/relativeLayout_over_youtube_thumbnail"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#color/color_background_transparent"
android:visibility="visible">
<ImageView android:id="#+id/btnYoutube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
android:src="#mipmap/ic_youtube_play_button"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Main Layout :
<?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">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I have 2 recycler views, let's call then recycler1 and recycler2 (purple background). The squares with yellow background are elements of recycler2 which has an instance inside of each element of recycler1. What I'm trying to achieve is that it should scroll elements of recycler2 on purple area fling and recycler1 outside it. I made it with horizontal scroll (which is very easy) but can't do it vertically. I tried to set and reset nested scrolling and behaviour and whatever but can't make it work.
Below the code (a lot of it):
InnerItem Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_height="50dp"
android:layout_width="60dp"
android:background="#38f"
android:padding="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:background="#ffff00"
android:id="#+id/tag_text_view"
android:text="Some Content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Nested recycler item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cfcfcf"
>
<TextView
android:id="#+id/first_name_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textSize="20sp"
android:text="New Text"
android:background="#1ad"
/>
<TextView
android:id="#+id/last_name_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:gravity="center"
android:layout_margin="10dp"
android:textSize="16sp"
android:padding="10dp"
android:background="#d65"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/nested_recycler"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#659"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
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="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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
InnerItem
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
public class InnerItem {
String tag;
public InnerItem(String tag) {
this.tag = tag;
}
}
InnerItem Adapter
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yrs.androidltx.R;
import java.util.List;
public class InnerItemAdapter extends RecyclerView.Adapter<InnerItemViewHolder> {
List<InnerItem> innerItemList;
public InnerItemAdapter(List<InnerItem> innerItemList) {
this.innerItemList = innerItemList;
}
#Override
public InnerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.inner_item, parent, false);
InnerItemViewHolder viewHolder = new InnerItemViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(InnerItemViewHolder holder, int position){
holder.tagTextVIew.setText(innerItemList.get(position).tag);
}
#Override
public int getItemCount() {
return innerItemList.size();
}
}
InnerItem ViewHolder
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.yrs.androidltx.R;
public class InnerItemViewHolder extends RecyclerView.ViewHolder {
TextView tagTextVIew;
public InnerItemViewHolder(View itemView) {
super(itemView);
tagTextVIew = (TextView) itemView.findViewById(R.id.tag_text_view);
}
}
Person
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Person ViewHolder
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.yrs.androidltx.R;
public class PersonViewHolder extends RecyclerView.ViewHolder {
//Keep package visibility
TextView firstNameTextView;
TextView lastNameTextView;
RecyclerView nestedRecyclerView;
public PersonViewHolder(View itemView) {
super(itemView);
firstNameTextView = (TextView) itemView.findViewById(R.id.first_name_textView);
lastNameTextView = (TextView) itemView.findViewById(R.id.last_name_textView);
nestedRecyclerView = (RecyclerView) itemView.findViewById(R.id.nested_recycler);
}
}
Person Adapter
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yrs.androidltx.R;
import java.util.ArrayList;
import java.util.List;
public class PersonAdapter extends RecyclerView.Adapter<PersonViewHolder> {
List<Person> personList;
public PersonAdapter(List<Person> personList) {
this.personList = personList;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.nested_recycler_item, parent, false);
PersonViewHolder personViewHolder = new PersonViewHolder(view);
return personViewHolder;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.firstNameTextView.setText(personList.get(position).getFirstName());
holder.lastNameTextView.setText(personList.get(position).getLastName());
holder.nestedRecyclerView.setLayoutManager(new GridLayoutManager(holder.nestedRecyclerView.getContext(), 3, GridLayoutManager.VERTICAL, false ));
holder.nestedRecyclerView.setAdapter(new InnerItemAdapter(initTagList()));
}
#Override
public int getItemCount() {
return personList.size();
}
private List<InnerItem> initTagList() {
List<InnerItem> tagList = new ArrayList<>();
tagList.add(new InnerItem("android"));
tagList.add(new InnerItem("iOS"));
tagList.add(new InnerItem("windows"));
tagList.add(new InnerItem("linux"));
tagList.add(new InnerItem("NetBSD"));
tagList.add(new InnerItem("NetWare"));
//repeat few times...
return tagList;
}
}
Main activity
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.yrs.androidltx.R;
import com.yrs.androidltx.activities.base.BaseActivity;
import java.util.ArrayList;
import java.util.List;
public class WithNestedRecyclerActivity extends BaseActivity {
private RecyclerView recyclerView;
private PersonAdapter personAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_recycler);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
personAdapter = new PersonAdapter(initDataSet());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(personAdapter);
}
private List<Person> initDataSet() {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Ned","Flanders"));
personList.add(new Person("Homer","Simpson"));
personList.add(new Person("Bart","Simpson"));
personList.add(new Person("Mr","Burns"));
//... repeat few times
return personList;
}
}