I'm trying to create a cardview album recycler view and as I was finishing up my code I found out that my program is displaying the same cardview for all three tab layouts. I want to display different cardview album for different tab layouts.Any help please!! Here is my program output.
program output
private RecyclerView recyclerView;
private AlbumAdapter adapter;
private List<Album> albumList;
#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.recycler_view);
albumList = new ArrayList<>();
adapter = new AlbumAdapter(this, albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
prepareAlbums();
try
{
Glide.with(this).load(R.drawable.cover);
} catch (Exception e)
{
e.printStackTrace();
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(MyFragment.newInstance("Home Fragment"), "Featured");
adapter.addFragment(MyFragment.newInstance("Events Fragment"), "Just Arrived");
adapter.addFragment(MyFragment.newInstance("Settings Fragment"), "Upcoming");
adapter.addFragment(MyFragment.newInstance("Settings Fragment"), "Upcoming");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
//adding viewpager to the tab-layout
tabLayout.setupWithViewPager(viewPager);
/**
* To have icons along with text but these icons will not change on selection of the tabs.
* So use the selector for the icons to change.
*/
tabLayout.getTabAt(0).setIcon(R.drawable.ic_menu_camera);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_menu_share);
// using selector for icons
tabLayout.getTabAt(2).setIcon(R.drawable.ic_menu_slideshow);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
/**
* Adding few albums for testing
*/
private void prepareAlbums() {
int[] covers = new int[]{
R.drawable.album1,
R.drawable.album2,
R.drawable.album3,
R.drawable.album4,
R.drawable.album5,
R.drawable.album6,
R.drawable.album7,
R.drawable.album8,
R.drawable.album9,
R.drawable.album10,
R.drawable.album11
};
Album a = new Album("hello", "Price: $2",covers[0]);
albumList.add(a);
a = new Album("Sugar", "Price: $6", covers[1]);
albumList.add(a);
a = new Album("Bon", "Price: $6", covers[2]);
albumList.add(a);
a = new Album("The lazy","Price: $7", covers[3]);
albumList.add(a);
a = new Album("The Cranberries", "Price: $3", covers[4]);
albumList.add(a);
a = new Album("West", "Price: $2", covers[5]);
albumList.add(a);
a = new Album("Black ", "Price: $2", covers[6]);
albumList.add(a);
a = new Album("Viva", "Price: $2", covers[7]);
albumList.add(a);
a = new Album("Cardigans", "Price: $12", covers[8]);
albumList.add(a);
a = new Album("Dolls", "Price: $2", covers[9]);
albumList.add(a);
adapter.notifyDataSetChanged();
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
//return mFragmentList.get(position);
switch (position) {
case 0:
MyFragment tab1 = new MyFragment();
return tab1;
case 1:
myfrag2 tab2 = new myfrag2();
return tab2;
case 2:
myfrag3 tab3 = new myfrag3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Here's my albumAdapter class
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.MyViewHolder> {
private Context mContext;
private List<Album> albumList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public AlbumAdapter(Context mContext, List<Album> albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Album album = albumList.get(position);
holder.title.setText(album.getName());
holder.count.setText(album.getPrice());
// loading album cover using Glide library
Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_album, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_play_next:
Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
#Override
public int getItemCount() {
return albumList.size();
}
}
My recyclerAdapter class
public class RecyclerAdapter extends RecyclerView.Adapter {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
Here's my first fragment class
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
return v;
}
public static MyFragment newInstance(String text) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
Here's my second fragment
public class myfrag2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout2, container, false);
return v;
}
}
here's my third frag
public class myfrag3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout3, container, false);
return v;
}
}
Related
ViewPager2 is scrolling to the wrong page when I am selecting a tab from a far position. Swiping and selecting tab of loaded pages working fine. The error is only happening when the page is not loaded and scrolling animation is active. I have created a large viewpager2 with 100 pages containing Recyclerview.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = findViewById(R.id.tabLayout);
ViewPager2 viewPager = findViewById(R.id.viewPager2);
viewPager.setAdapter(new viewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager, true, true,
((tab, position) -> tab.setText("Page: " + position))).attach();
}
private class viewPagerAdapter extends FragmentStateAdapter {
public viewPagerAdapter(FragmentActivity fa) {
super(fa);
}
#Override
public Fragment createFragment(int position) {
Fragment fragment = new itemFragment();
Bundle args = new Bundle();
args.putInt(itemFragment.ARG_PARAM1, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getItemCount() {
return 100;
}
}
}
My Fragment
public class itemFragment extends Fragment {
public static final String ARG_PARAM1 = "parram1";
int pagePosition;
public itemFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagePosition = getArguments().getInt(ARG_PARAM1);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frgment_item, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = view.findViewById(R.id.textView);
textView.setText("Page - " + pagePosition);
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setAdapter(new myAdapter());
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 16));
}
private class myAdapter extends RecyclerView.Adapter<Myvh> {
#Override
public Myvh onCreateViewHolder(ViewGroup parent, int viewType) {
return new Myvh(new TextView(getContext()));
}
#Override
public void onBindViewHolder(Myvh holder, int position) {
int codepoint=pagePosition*700 + position;
char[] ch=Character.toChars(codepoint);
holder.textView.setText(String.valueOf(ch));
}
#Override
public int getItemCount() { return 700; }
}
private class Myvh extends RecyclerView.ViewHolder {
TextView textView;
public Myvh(View itemView) {
super(itemView);
textView = (TextView) itemView;
}
}
}
I have also tried Recyclerview adapter instead of FragmentStateAdapter and getting same problem.
I have found some solution but not sufficient.
Those are:
Using old ViewPager(deprecated)
Using viewPager.setOffscreenPageLimit(100); (taking huge time to load activity)
Disabling smoothscroll ( looks awful when swiping)
Hi I want to send the data ArrayList<Division> to Fragment class ListContentFragment.
In MainActivity I am making a network call to get the data(JSON) and then parsing it to create ArrayList<Division>, now i want to populate the list view with the data i received (now in ArrayList<Division>)
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
// Create Navigation drawer and inlfate layout
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
// Adding menu icon to Toolbar
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
VectorDrawableCompat indicator
= VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
indicator.setTint(ResourcesCompat.getColor(getResources(),R.color.white,getTheme()));
supportActionBar.setHomeAsUpIndicator(indicator);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
// Set behavior of Navigation drawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Set item in checked state
menuItem.setChecked(true);
// TODO: handle navigation
Toast.makeText(MainActivity.this, "Clicked: " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();
// Closing drawer on item click
mDrawerLayout.closeDrawers();
return true;
}
});
// Adding Floating Action Button to bottom right of main view
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Hello Snackbar!",
Snackbar.LENGTH_LONG).show();
}
});
// Network request test with volley
NetworkRequests networkRequest = new NetworkRequests(this);
networkRequest.fetchDummyData();
divisionList = networkRequest.getDivisions();
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new ListContentFragment(), "List");
adapter.addFragment(new TileContentFragment(), "Tile");
adapter.addFragment(new CardContentFragment(), "Card");
viewPager.setAdapter(adapter);
}
Fragment (currently its hard coded, want to populate with the ArrayList)
public class ListContentFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView avator;
public TextView name;
public TextView description;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_list, parent, false));
avator = (ImageView) itemView.findViewById(R.id.list_avatar);
name = (TextView) itemView.findViewById(R.id.list_title);
description = (TextView) itemView.findViewById(R.id.list_desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
context.startActivity(intent);
}
});
}
}
/**
* Adapter to display recycler view.
*/
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private static final int LENGTH = 18;
private final String[] mPlaces;
private final String[] mPlaceDesc;
private final Drawable[] mPlaceAvators;
public ContentAdapter(Context context) {
Resources resources = context.getResources();
mPlaces = resources.getStringArray(R.array.places);
mPlaceDesc = resources.getStringArray(R.array.place_desc);
TypedArray a = resources.obtainTypedArray(R.array.place_avator);
mPlaceAvators = new Drawable[a.length()];
for (int i = 0; i < mPlaceAvators.length; i++) {
mPlaceAvators[i] = a.getDrawable(i);
}
a.recycle();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.avator.setImageDrawable(mPlaceAvators[position % mPlaceAvators.length]);
holder.name.setText(mPlaces[position % mPlaces.length]);
holder.description.setText(mPlaceDesc[position % mPlaceDesc.length]);
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}
If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable.
Here i can show an example.
public class ObjectName implements Parcelable {
public ObjectName(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<ObjectName> CREATOR = new Parcelable.Creator<ObjectName>() {
public ObjectName createFromParcel(Parcel in) {
return new ObjectName(in);
}
public ObjectName[] newArray(int size) {
return new ObjectName[size];
}
};
public void readFromParcel(Parcel in) {
Value1 = in.readInt();
Value2 = in.readInt();
Value3 = in.readInt();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Value1);
dest.writeInt(Value2);
dest.writeInt(Value3);
}
}
then you can add ArrayList<ObjectName> to a Bundle object.
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
fragment.setArguments(bundle);
After this you can get back this data by using,
Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("arraylist");
At last you can show list with these data in fragment. Hope this will help to get your expected answer.
I was also stuck with the same problem .
You can try this.
Intead of sending the arraylist as bundle to fragment.Make the arraylist to be passed,as public and static in the activity.
public static Arraylist<Division> arraylist;
Then after parsing and adding the data in the arraylist make the call to the fragment.In the fragment you can the use the arraylist as:
ArrayList<Division> list=MainActivity.arraylist;
I'm trying to add an Object to this RecycleView. When I add the objects to the initial ArrayList they all show up. However, when I try to add an object and call notifyDataSetChanged from HomeFragment, nothing happens on the UI.
HomeFragment.java
public class HomeFragment extends Fragment {
View myView;
private RecyclerView mRecyclerView;
private HomeAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ArrayList<Note> myNotes;
private Activity activity;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myView = inflater.inflate(R.layout.first_layout, container, false);
mRecyclerView = (RecyclerView) myView.findViewById(R.id.list12313);
//linear layout manager
mLayoutManager = new LinearLayoutManager(activity);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//adapter
myNotes = new ArrayList<Note>();
myNotes.add(new Note("Welcome to WITS Mobile", "Logged in as: " + LoginActivity.witsName));
myNotes.add(new Note("Version 0.1 ALPHA", "- Early Internal Alpha"));
//myNotes.add(new Note());
mAdapter = new HomeAdapter(myNotes, activity);
mRecyclerView.setAdapter(new SlideInBottomAnimationAdapter(mAdapter));
setHasOptionsMenu(true);
return myView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.first, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_add:
addItem();
return true;
case R.id.action_CLR:
clear();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addItem()
{
Note e = new Note("New Title", "New Body");
mAdapter.addItem(e);
}
public void clear()
{
mAdapter.clear();
}
}
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder>
{
private ArrayList<Note> mNotes;
private int lastPosition = -1;
private Context context;
public HomeAdapter(ArrayList<Note> list, Context context)
{
this.mNotes = list;
this.context = context;
}
public void clear()
{
mNotes.clear();
notifyDataSetChanged();
}
public void addItem(Note n)
{
System.out.println("add");
mNotes.add(n);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder
{
public View view;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
}
}
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
//create new view
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_card, viewGroup, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
public TextView title;
public TextView subtext;
#Override
public void onBindViewHolder(HomeAdapter.ViewHolder viewHolder, int i)
{
//Replace contents of a view, called by layout manager
title = (TextView) viewHolder.view.findViewById(R.id.title);
subtext = (TextView) viewHolder.view.findViewById(R.id.subtext);
title.setText(mNotes.get(i).getTitle());
subtext.setText(mNotes.get(i).getBody());
setAnimation(viewHolder.view, i);
}
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mNotes.size();
}
}
Take out this line:
mRecyclerView.setHasFixedSize(true);
Fixed size means the count of the items, not the layout size
i have followed Slidenerd's tutorial on youtube on how to create a material design navigation drawer using android studio.
However on running the app i get this cannot resolve method getData() and on the console Error:(56, 46) error: cannot find symbol method getData() error onadapter=new AdapterClass(getActivity().getData());
There's probably somewhere i have overlooked.Any help will be appreciated.
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private View containerView;
private AdapterClass adapter;
private RecyclerView recyclerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView=(RecyclerView)layout.findViewById(R.id.drawerList);
adapter=new AdapterClass(getActivity().getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check, R.drawable.ic_menu_check};
String[] titles = {"Notifications", "School", "What's hot", "Hit us up"};
for (int i=0;i<titles.length && i<icons.length;i++)
{
Information current=new Information();
current.iconId=icons[i];
current.title=titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#SuppressLint("NewApi")
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#SuppressLint("NewApi")
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
AdapterClasss.java
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
private LayoutInflater inflater;
List<Information>data= Collections.emptyList();
public AdapterClass(Context context,List<Information>data){
inflater= LayoutInflater.from(context);
this.data=data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= inflater.inflate(R.layout.custom_row,parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current=data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.listText);
icon=(ImageView)itemView.findViewById(R.id.listIcon);
}
}
}
adapter = new VivzAdapter(getActivity(),getData());
use this intead
adapter=new AdapterClass(getActivity().getData());
i had the same problem. ;-)
Fixed it by doing it this way:
adapter = new AdapterClass(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
This is my page:
package[...]
import [...]
public class Home extends FragmentActivity {
ViewPager mViewPager;
ListView list;
row_video_Adapter adapter;
public Home CustomListView = null;
public ArrayList<ModelloLista> CustomListViewValuesArr = new ArrayList<ModelloLista>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// ListView
CustomListView = this;
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
setListData();
Resources res =getResources();
list= (ListView)findViewById(R.id.section_label); // List defined in XML ( See Below )
/**************** Create Custom Adapter *********/
adapter=new row_video_Adapter(CustomListView, CustomListViewValuesArr,res);
list.setAdapter(adapter);
}
/****** Function to set data in ArrayList *************/
public void setListData(){
final ModelloLista sched = new ModelloLista();
sched.setTitolo("Video 1");
sched.setImmagine("video_preview");
sched.setUrl("http:\\www.com");
CustomListViewValuesArr.add(sched);
}
/***************** This function used by adapter ****************/
public void onItemClick(int mPosition){
ModelloLista tempValues = ( ModelloLista ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
[...]
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
//dummyTextView.setText("text 1");
break;
case 2:
[...]
}
return rootView;
}
}
}
How can I put my Custom ListView in a fragment?
I tried to move the code in the switch(getArguments().getInt(ARG_SECTION_NUMBER)){ but there were many errors.
What should I do?