I want my 2 columns RecyclerView, i.e. using GridLayoutManager, inside scrollview. I found a way to put single column recyclerview inside scrollview from this link, but i cant figure out how to put Grid RecyclerView inside scrollview.
I found solution. Work perfect for me.
my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_grid_recycler_view"
tools:context="com.example.recyclerview_horizontal.GridRecyclerView">
<ScrollView
android:layout_width="match_parent"
android:fillViewport="true"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
android:layout_marginBottom="50dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="300dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gridview inside scrollview"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
MainActivity
package com.example.gridrecyclerviewscroll;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements RecyclerAdapter.DynamicHeight {
RecyclerView recyclerView;
RecyclerAdapter adapter;
ArrayList<Integer> list;
ArrayList<Integer> size;
TextView txt;
long sumHeight=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager lm = new GridLayoutManager(this,2);
// txt = (TextView) findViewById(R.id.txt1);
recyclerView.setLayoutManager(lm);
size = new ArrayList<>();
list = new ArrayList<>();
list.add(R.drawable.index1);
list.add(R.drawable.index2);
list.add(R.drawable.index3);
list.add(R.drawable.index4);
list.add(R.drawable.index5);
list.add(R.drawable.index6);
list.add(R.drawable.index8);
list.add(R.drawable.index9);
list.add(R.drawable.index10);
adapter = new RecyclerAdapter(list,this);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void HeightChange(int position, int height) {
size.add(height);
sumHeight = calSum();
float density = this.getResources().getDisplayMetrics().density;
float viewHeight = sumHeight * density;
recyclerView.getLayoutParams().height = (int) sumHeight;
}
private long calSum() {
long tot=0;
for(int i=0;i<size.size();i++){
tot = tot + size.get(i);
}
return tot;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
RecyclerViewAdapter
package com.example.gridrecyclerviewscroll;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by nteam on 23/10/15.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Integer> list;
Context context;
private DynamicHeight dynamicHeight;
public RecyclerAdapter(ArrayList<Integer> list, DynamicHeight dynamicHeight){
this.list = list;
this.dynamicHeight = dynamicHeight;
}
public RecyclerAdapter(ArrayList<Integer> list){
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_card,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.img.setImageResource(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView img;
public ViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img_thumbnail);
}
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position, List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
holder.itemView.post(new Runnable() {
#Override
public void run() {
int cellwidth = holder.itemView.getWidth();
int cellheight = holder.itemView.getHeight();
if(dynamicHeight!=null) dynamicHeight.HeightChange(position, cellheight);
}
});
}
public interface DynamicHeight {
void HeightChange(int position, int height);
}
}
All credits goes to #Ashkan
Related
I have a button that says ADD ITEM.
Below there is a RECYCLERVIEW.
When you click on ADD ITEM it adds an EDITVIEW to the recycler view. You type text in it, and then click on ADD ITEM again and it adds another EDITVIEW to the recyler view.
Everything is in the right order.
When you click on ADD ITEM for the 4th time, instead of adding at the 4th position, it adds at the 1st position and moves the previous 3 items down 1.
What could be causing this?
Main Activity
package com.app.bowling.animalsrecycler;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import static java.sql.Types.NULL;
public class MainActivity extends Activity implements RemoveClickListner{
private RecyclerView mRecyclerView;
private RecyclerAdapter mRecyclerAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Button btnAddItem;
ArrayList<RecyclerData> myList = new ArrayList<>();
EditText etTitle;
String title = "";
ImageView crossImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerAdapter = new RecyclerAdapter(myList,this);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
mRecyclerView.setAdapter(mRecyclerAdapter);
etTitle = (EditText) findViewById(R.id.etTitle);
if (mRecyclerAdapter.getItemCount() == 0 || mRecyclerAdapter.getItemCount() == NULL){
Toast.makeText(getApplicationContext(),"ZERO ITEMS LISTED",Toast.LENGTH_SHORT).show();
}
btnAddItem = (Button) findViewById(R.id.btnAddItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
title = etTitle.getText().toString();
// if (title.matches("")) {
// Toast.makeText(v.getContext(), "You did not enter a Title", Toast.LENGTH_SHORT).show();
// return;
// }
RecyclerData mLog = new RecyclerData();
// mLog.setTitle(title);
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
if (mRecyclerAdapter.getItemCount() > 0) {
Toast.makeText(v.getContext(), mRecyclerAdapter.getItemCount() + " Items Displayed", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
#Override
public void OnRemoveClick(int index) {
myList.remove(index);
mRecyclerAdapter.notifyData(myList);
}
}
RecyclerAdapter
package com.app.bowling.animalsrecycler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerItemViewHolder> {
private ArrayList<RecyclerData> myList;
int mLastPosition = 0;
private RemoveClickListner mListner;
public RecyclerAdapter(ArrayList<RecyclerData> myList,RemoveClickListner listner) {
this.myList = myList;
mListner=listner;
}
public RecyclerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
RecyclerItemViewHolder holder = new RecyclerItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerItemViewHolder holder, final int position) {
Log.d("onBindViewHolder ", myList.size() + "");
mLastPosition = position;
holder.crossImage.setImageResource(R.drawable.ic_add_circle_black_24dp);
holder.etTitleTextView.setHint("Enter Player " + (position + 1));
holder.etTitleTextView.requestFocus();
}
#Override
public int getItemCount() {
return(null != myList?myList.size():0);
}
public void notifyData(ArrayList<RecyclerData> myList) {
Log.d("notifyData ", myList.size() + "");
this.myList = myList;
notifyDataSetChanged();
}
public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {
private final TextView etTitleTextView;
private ConstraintLayout mainLayout;
public ImageView crossImage;
public RecyclerItemViewHolder(final View parent) {
super(parent);
etTitleTextView = parent.findViewById(R.id.txtTitle);
etTitleTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myList.get(getAdapterPosition()).setTitle(etTitleTextView.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
crossImage = (ImageView) parent.findViewById(R.id.crossImage);
mainLayout = (ConstraintLayout) parent.findViewById(R.id.mainLayout);
mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
}
});
crossImage.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
mListner.OnRemoveClick(getAdapterPosition()
);
}
});
}
}
RecyclerData
package com.app.bowling.animalsrecycler;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
public class RecyclerData {
String title;
RecyclerView data;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setCrossImage(ImageView crossImage){
setCrossImage(crossImage);
}
}
RemoveClickLstner
package com.app.bowling.animalsrecycler;
public interface RemoveClickListner {
void OnRemoveClick(int index);
}
Activity_Main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:padding="16dp"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:id="#+id/etTitle" />
<Button
android:id="#+id/btnAddItem"
android:text="Add Item"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbfffe" />
</LinearLayout>
RecyclerView_Item
<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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:id="#+id/cardview"
android:layout_height="112dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/txtTitle"
android:maxLines="1"
android:inputType="text"
android:maxLength="15"
android:layout_width="273dp"
android:layout_height="56dp"
android:layout_marginEnd="122dp"
android:layout_marginBottom="56dp"
android:padding="12dp"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
<ImageView
android:id="#+id/crossImage"
android:layout_width="136dp"
android:layout_height="112dp"
android:layout_marginStart="273dp"
android:background="#drawable/ic_add_circle_black_24dp"
android:paddingLeft="10dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
</android.support.constraint.ConstraintLayout>
</LinearLayout>
Just try to replace your below snippet
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
Add this:
myList.add(mLog);
mRecyclerAdapter.addAll(myList);
mRecyclerAdapter.notifyDataSetChanged();
etTitle.setText("");
I would like to see your layout activity_main and recycler_view item because I have tried implementing your code with few twist and the code is working well please check the code below
https://github.com/muchbeer/StackOverflowRecyclerView
Please find the below Screen Shot
Kindy let me if this was your intended application
hello please I need help
I want to add an Edittext to use it for search for recycleview
my program will be run without crashing but it not work
in my project I have a BottomNavigation (fragment) and inside it I used Tablayout (fragment) (a fragment inside another fragment (Tab inside bottom navigation))
I have no error but my search is not working
**If It is possible for you , please add this code inside your new blank project and test it and help me **
I used this search totorial by this learning project
https://codinginflow.com/tutorials/android/searchview-recyclerview
My Main Activity code is(Fragment of BottomNavigation is inside MainActicity)
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
//call Fragments class
private BottomNavigationFragment fragmentOne;
/* private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;*/
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
setFragment(fragmentOne);
return true;
case R.id.navigation_dashboard:
/*
setFragment(fragmentTwo);
*/
return true;
case R.id.navigation_notifications:
/*
setFragment(fragmentThree);
*/
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//make new from fragments
//fragment of BottomNavigation
fragmentOne = new BottomNavigationFragment();
/* fragmentThree = new FragmentThree();
fragmentTwo = new FragmentTwo();
*/
setFragment(fragmentOne);
frameLayout = findViewById(R.id.main_fream);
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_fream, fragment);
fragmentTransaction.commit();
}
}
My Layout Of main_activity.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/main_fream"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
My Bottom Navigation Fragment class
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class BottomNavigationFragment extends Fragment {
TabLayout tabLayout;
EditText search;
ViewPager viewPager;
public BottomNavigationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_bottom_navigation, container, false);
search=view.findViewById(R.id.searchinfragmentOne);
tabLayout=view.findViewById(R.id.tablayout_id);
viewPager=view.findViewById(R.id.viewpager);
ViewPagerAdapterForTabs adapter = new ViewPagerAdapterForTabs(getChildFragmentManager());
// this is Tab Fragments
adapter.AddFragment(new TabFragment(),"Tab1");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
**and My Layout Of this Buttom Navigation **
<?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"
android:orientation="vertical"
tools:context=".BottomNavigationFragment">
<EditText
android:id="#+id/searchinfragmentOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="search ..." />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
app:tabGravity="fill"
app:tabIndicatorColor="#color/colorPrimary"
app:tabMode="scrollable"
app:tabTextColor="#color/colorPrimaryDark" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
Tab Fragment
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class TabFragment extends Fragment {
public List<Items> lstItems;
public RecyclerViewAdapter mAdapter;
EditText search;
public TabFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
lstItems = new ArrayList<>();
lstItems.add(new Items("a", "11265", "27500", "horizental", R.drawable.gemtv));
lstItems.add(new Items("b", "11265", "27500", "horizental", R.drawable.bbc));
lstItems.add(new Items("c", "11265", "27500", "horizental", R.drawable.voa));
lstItems.add(new Items("d", "11265", "27500", "horizental", R.drawable.manoto));
search = view.findViewById(R.id.searchintabbadrkurdi);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
/*mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new RecyclerViewAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);*/
return view;
}
private void filter(String text) {
ArrayList<Items> filteredList = new ArrayList<>();
for (Items item : lstItems) {
if (item.getTvName().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
}
Tab Layout . xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".TabFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/searchintabbadrkurdi"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview_id_badr_kurdi"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</FrameLayout>
My Item Class
package forokans.sirwansoft.forlearn;
public class Items {
private String TvName;
private String Forekans;
private String BistoHaft;
private String Horizental;
private int ImageSrc;
//main constructor
public Items() {
}
// constructor
public Items(String tvName, String forekans, String bistoHaft, String horizental, int imageSrc) {
TvName = tvName;
Forekans = forekans;
BistoHaft = bistoHaft;
Horizental = horizental;
ImageSrc = imageSrc;
}
//getter
public String getTvName() {
return TvName;
}
//getter
public String getForekans() {
return Forekans;
}
public String getBistoHaft() {
return BistoHaft;
}
//getter
public int getImageSrc() {
return ImageSrc;
}
public String getHorizental() {
return Horizental;
}
}
My Recycler View Adapter Class
package forokans.sirwansoft.forlearn;
import android.content.Context;
import android.support.v7.widget.CardView;
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 android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<Items> lstItems;
public RecyclerViewAdapter(Context mContext, List<Items> lstItems) {
this.mContext = mContext;
this.lstItems = lstItems;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.recycler_view_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
//in main activity displays
holder.tv_Items_TvName.setText(lstItems.get(position).getTvName());
holder.tv_Items_cat.setText(lstItems.get(position).getForekans());
holder.tv_Items_desc.setText(lstItems.get(position).getBistoHaft());
holder.tv_Items_horizental.setText(lstItems.get(position).getHorizental());
holder.img_Items_ImageSrc.setImageResource(lstItems.get(position).getImageSrc());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return lstItems.size();
}
public void filterList(ArrayList<Items> filteredList) {
lstItems = filteredList;
notifyDataSetChanged();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Items_TvName;
TextView tv_Items_cat;
TextView tv_Items_desc;
TextView tv_Items_horizental;
ImageView img_Items_ImageSrc;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
tv_Items_TvName = itemView.findViewById(R.id.Items_TvName_id);
tv_Items_cat = itemView.findViewById(R.id.Items_cat_id);
tv_Items_desc = itemView.findViewById(R.id.Items_desc_id);
tv_Items_horizental = itemView.findViewById(R.id.Items_Hor_id);
img_Items_ImageSrc = itemView.findViewById(R.id.Items_img_id);
cardView = itemView.findViewById(R.id.cardview_id);
}
}
}
And My ViewPagerAdapter class For Tabs
package forokans.sirwansoft.forlearn;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapterForTabs extends FragmentPagerAdapter {
private final List<Fragment> FragmentList = new ArrayList<>();
private final List<String> FragmentListTitles = new ArrayList<>();
public ViewPagerAdapterForTabs(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentList.get(position);
}
#Override
public int getCount() {
return FragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return FragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment, String titles) {
FragmentList.add(fragment);
FragmentListTitles.add(titles);
}
}
i found out
change this
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
to this
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
the reason is
before We call onCreate this RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems); was initialized and in last one if we make this class a new abject , it will be a new initializing value
I'm new with android firebase. My problem is that I would like to display the list of my data in the database in a
recycleview. I have a tablayout that contains 3 tabs. it's in the first tab that I want to display my data, I use a fragment
in which I met my recycleview, i also the method
Blockquote
addValueEventListener
Blockquote
to take my firebase data. Whenever I launch the application it displays nothing I have this message
Blockquote
E / RecyclerView: No adapter attached; skip the layout
Blockquote
.Is this someone can help me. Thanks in Advance
My Firebase Data[1]: https://imgur.com/gallery/uIOEPuA
HomeActivity.java
package com.example.saincurin.htfacile;
import android.os.Build;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabItem;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.saincurin.htfacile.Adapters.PageAdapter;
public class HomeActivity extends AppCompatActivity {
private Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
private DrawerLayout mDrawer;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.toolbar);
mDrawer = findViewById(R.id.drawer_layout);
nvDrawer = findViewById(R.id.nvView);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
// Set up Drawer View
PagerAdapter pagerAdapter = new PageAdapter(getSupportFragmentManager(), HomeActivity.this);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(HomeActivity.this,
R.color.colorAccent));
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar,
R.string.drawer_open, R.string.drawer_close);
mDrawer.addDrawerListener(toggle);
toggle.syncState();
// give the Tablayout the viewPager
tabLayout.setupWithViewPager(viewPager);
// setupDrawerContent(nvDrawer);
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.START)) {
mDrawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// private void setupDrawerContent(NavigationView navigationView) {
// navigationView.setNavigationItemSelectedListener(
// new NavigationView.OnNavigationItemSelectedListener() {
// #Override
// public boolean onNavigationItemSelected(MenuItem menuItem) {
// selectDrawerItem(menuItem);
// return true;
// }
// });
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_products, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_more) {
Toast.makeText(this, "The more is selected", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == R.id.action_search) {
Toast.makeText(this, "The search is selected", Toast.LENGTH_SHORT ).show();
}else if (item.getItemId() == R.id.drawer_layout) {
mDrawer.openDrawer(GravityCompat.START);
}
return true;
}
}
My Model
package com.example.saincurin.htfacile.ModelData;
public class DataModel {
private String description;
private String name;
private String image;
private String price;
private String quantity;
//constructor
public DataModel() {
}
public DataModel(String name, /*String description,*/ String image, String price) {
this.name = name;
// this.description = description;
this.image = image;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
My Adapter
package com.example.saincurin.htfacile.Adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.saincurin.htfacile.ModelData.DataModel;
import com.example.saincurin.htfacile.R;
import com.squareup.picasso.Picasso;
import java.util.List;
// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductsviewHolder> {
private Context mcontext;
// Store a member variable for the contacts
private List<DataModel> mDataModel;
public ProductsAdapter(Context context, List<DataModel> mDataModel) {
mcontext = context;
this.mDataModel = mDataModel;
}
// Usually involves inflating a layout from XML and returning the holder
#NonNull
#Override
public ProductsviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate the custom Layout
View dataView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
//return a new holder instance
return new ProductsviewHolder(dataView);
}
// Involves populating data into the item through holder
#Override
public void onBindViewHolder(#NonNull ProductsviewHolder holder, int position) {
// Get the data model based on position
DataModel dataModel = mDataModel.get(position);
// Set item views based on your views and data model
holder.txtName.setText(dataModel.getName());
// holder.txtDescription.setText(dataModel.getDescription());
holder.txtPrice.setText(dataModel.getPrice());
Picasso.with(mcontext)
.load(dataModel.getImage())
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public class ProductsviewHolder extends RecyclerView.ViewHolder {
public TextView txtName;
// public TextView txtDescription;
public TextView txtPrice;
public TextView txtQuantity;
public ImageView imageView;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ProductsviewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
txtName = itemView.findViewById(R.id.rvTitleTv);
// txtDescription = itemView.findViewById(R.id.rDescriptionTv);
txtPrice = itemView.findViewById(R.id.rPrice);
imageView = itemView.findViewById(R.id.rImageView);
}
}
}
My first Fragment tab
package com.example.saincurin.htfacile.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.saincurin.htfacile.Adapters.ProductsAdapter;
import com.example.saincurin.htfacile.ModelData.DataModel;
import com.example.saincurin.htfacile.R;
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 java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class ProductsFragment extends Fragment {
private RecyclerView mRecycleView;
private ProductsAdapter mProductsAdapter;
private DatabaseReference mReference;
private List<DataModel> mDataModel;
View v;
public ProductsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_products, container, false);
//RecycleView
mRecycleView = v.findViewById(R.id.recycleView);
mRecycleView.setHasFixedSize(true);
//set Layout as LinearLayout
mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
mDataModel = new ArrayList<>();
//send Query FirebaseDatabase
mReference = FirebaseDatabase.getInstance().getReference("uploads");
Log.e("DEBUG", "The Reference :"+mReference);
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
DataModel dataModel = postSnapshot.getValue(DataModel.class);
mDataModel.add(dataModel);
}
// Log.e("DEBUG","The data model "+ mDataModel.toString());
mProductsAdapter = new ProductsAdapter(getContext(), mDataModel);
// Log.e("DEBUG","The data model "+ mProductsAdapter);
//set the adapter to the recyclerview
mRecycleView.setAdapter(mProductsAdapter);
mProductsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
return v;
}
}
Layout for my first tab pager
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".fragments.ProductsFragment">
<!--RecycleView-->
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Layout for my HomeActivity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".HomeActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
style="#style/myCustomTabLayout"
android:background="#color/colorPrimary"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#android:color/black">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
My item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.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="match_parent"
app:cardBackgroundColor="#fff"
app:cardCornerRadius="3dp"
app:cardElevation="3dp"
app:cardUseCompatPadding="true"
app:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/rvTitleTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="#000"
android:textSize="22sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/rImageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:adjustViewBounds="true"
android:background="#drawable/loading"
android:scaleType="center" />
<TextView
android:id="#+id/rPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="150 gdes"
android:textSize="20dp"
android:textStyle="bold" />
<!--<TextView-->
<!--android:id="#+id/rDescriptionTv"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="This is the post description that"-->
<!--android:textSize="20sp" />-->
</LinearLayout>
</android.support.v7.widget.CardView>
Welcome to StackOverflow. The RecyclerView is quite specific when it comes to its setup. So you need to make sure you set up the adapter before setting the layout manager and the fixedSize property.
Try changing your onCreateView method to this:
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_products, container, false);
// Notice that I changed the order of RecyclerView setup
mRecycleView = v.findViewById(R.id.recycleView);
mDataModel = new ArrayList<>();
mProductsAdapter = new ProductsAdapter(getContext(), mDataModel);
mRecyclerView.setAdapter(mProductsAdapter);
mRecycleView.setHasFixedSize(true);
//set Layout as LinearLayout
mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
//send Query FirebaseDatabase
mReference = FirebaseDatabase.getInstance().getReference("uploads");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
DataModel dataModel = postSnapshot.getValue(DataModel.class);
mDataModel.add(dataModel);
}
mProductsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
return v;
}
package com.android_examples.recyclerview_android_examplescom;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Context context;
RecyclerView recyclerView;
LinearLayout relativeLayout;
Button button;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
String[] subjects =
{
"ANDROID",
"PHP",
"BLOGGER",
"WORDPRESS",
"JOOMLA",
"ASP.NET",
"JAVA",
"C++",
"MATHS",
"HINDI",
"ENGLISH"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
context = getApplicationContext();
relativeLayout = (LinearLayout) findViewById(R.id.relativelayout1);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recylerViewLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(recylerViewLayoutManager);
recyclerViewAdapter = new RecyclerViewAdapter(context, subjects);
recyclerView.setAdapter(recyclerViewAdapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recylerViewLayoutManager.findViewByPosition(10).setBackgroundColor(Color.BLUE);
}
});
}
}
activity_main:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.android_examples.recyclerview_android_examplescom.MainActivity"
android:id="#+id/relativelayout1">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change"
android:id="#+id/button"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:scrollbars="vertical"
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
RecyclerAdapter:--
package com.android_examples.recyclerview_android_examplescom;
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.TextView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
String[] SubjectValues;
Context context;
View view1;
ViewHolder viewHolder1;
TextView textView;
public RecyclerViewAdapter(Context context1,String[] SubjectValues1){
SubjectValues = SubjectValues1;
context = context1;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ViewHolder(View v){
super(v);
textView = (TextView)v.findViewById(R.id.subject_textview);
}
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
view1 = LayoutInflater.from(context).inflate(R.layout.recyclerview_items,parent,false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position){
package com.android_examples.recyclerview_android_examplescom;
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.TextView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
String[] SubjectValues;
Context context;
View view1;
ViewHolder viewHolder1;
TextView textView;
public RecyclerViewAdapter(Context context1,String[] SubjectValues1){
SubjectValues = SubjectValues1;
context = context1;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ViewHolder(View v){
super(v);
textView = (TextView)v.findViewById(R.id.subject_textview);
}
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
view1 = LayoutInflater.from(context).inflate(R.layout.recyclerview_items,parent,false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position){
holder.textView.setText(SubjectValues[position]);
}
#Override
public int getItemCount(){
return SubjectValues.length;
}
}
holder.textView.setText(SubjectValues[position]);
}
#Override
public int getItemCount(){
return SubjectValues.length;
}
}
If i want to change the background of perticular item in Recyclerview from button click it will effect to only visible items only not for invisible means (first item is visible to user it will effect, but for last item it will not change the color )
Please Help me...
Thanks In advance..
OnItemClickListener Will give you the position of the view and you can use this below code for changing background of selected positioned row
private View SelectedItem;
private void BackColor(View view) {
if (SelectedItem != null) {
SelectedItem.setBackgroundColor(Color.TRANSPARENT);
}
view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
SelectedItem = view;
}
yourListview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
BackColor(view);
}
}
First get the click action of convertView (Object of View) under this set view as
if(!convertView.isSelected()){
convertView.setSelected(true);
//here change the background color as selected.
}else{
convertView.setSelected(false);
//here change the background color as unselected.
}
Handel isSelected status in selection.
How to get the convertView Object reference
I'm new in android... and i have find a staggered grid on github of two columns but i need to add another column to my staggered grid .... so how to add?? please help
Main Activity:
package com.grafixartist.masonry;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Staggered Grid");
}
mRecyclerView = (RecyclerView) findViewById(R.id.masonry_grid);
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
MasonryAdapter adapter = new MasonryAdapter(this);
mRecyclerView.setAdapter(adapter);
SpacesItemDecoration decoration = new SpacesItemDecoration(16);
mRecyclerView.addItemDecoration(decoration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Masonary Adaptor:
package com.grafixartist.masonry;
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;
/**
* Created by Suleiman on 26-07-2015.
*/
public class MasonryAdapter extends RecyclerView.Adapter<MasonryAdapter.MasonryView> {
private Context context;
int[] imgList = {R.drawable.two, R.drawable.one, R.drawable.three, R.drawable.four,
R.drawable.five, R.drawable.six, R.drawable.seven, R.drawable.eight,
R.drawable.nine, R.drawable.ten};
String[] nameList = {"One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten"};
public MasonryAdapter(Context context) {
this.context = context;
}
#Override
public MasonryView onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
MasonryView masonryView = new MasonryView(layoutView);
return masonryView;
}
#Override
public void onBindViewHolder(MasonryView holder, int position) {
holder.imageView.setImageResource(imgList[position]);
holder.textView.setText(nameList[position]);
}
#Override
public int getItemCount() {
return nameList.length;
}
class MasonryView extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public MasonryView(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.img);
textView = (TextView) itemView.findViewById(R.id.img_name);
}
}
}
SpacesItemDecoration:
package com.grafixartist.masonry;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by Suleiman on 26-07-2015.
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpace;
public SpacesItemDecoration(int space) {
this.mSpace = space;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = mSpace;
outRect.right = mSpace;
outRect.bottom = mSpace;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0)
outRect.top = mSpace;
}
}
activity_main.xml:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/quickreturn_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/masonry_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
grid_items.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/img_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="8dp" />
</LinearLayout>
Output:
Output
But i want to add one more column to staggered grid like below:
This is what i want
Try This:-
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
change to
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));