How to resolve 'getData()' method in recyclerview using android studio - java

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()));

Related

Nested RecyclerView OnclickListener to new fragment

**I want to know how to click the items in childRecyclerview show different fragment, I think we should try to modify childAdapter, I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
hear is my code
**
//workflow fragment
public class WorkflowFragment extends Fragment {
private Context mContext;
private String[] workflowHeading;
private String[] workflowContent;
private int[] imageResourceId;
private RecyclerView recyclerview;
private List<Workflow> workflowList;
private WorkflowAdapter workflowAdapter;
private View view;
public static WorkflowFragment newInstance(String param1, String param2) {
WorkflowFragment fragment = new WorkflowFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mContext = getActivity();
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view==null) {
view = inflater.inflate(R.layout.fragment_workflow, container, false);
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataInitialize();
recyclerview = view.findViewById(R.id.workflow_recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerview.setHasFixedSize(true);
workflowAdapter =new WorkflowAdapter(getContext(),workflowList);
recyclerview.setAdapter(workflowAdapter);
workflowAdapter.notifyDataSetChanged();
}
private void dataInitialize() {
//list1
List<String> nestedList1 = new ArrayList<>();
nestedList1.add("A");
nestedList1.add("B");
nestedList1.add("C");
nestedList1.add("D");
nestedList1.add("E");
nestedList1.add("F");
nestedList1.add("G");
//list2
List<String>nestedList2 = new ArrayList<>();
nestedList2.add("H");
nestedList2.add("I");
nestedList2.add("G");
nestedList2.add("K");
//list3
List<String>nestedList3 = new ArrayList<>();
nestedList3.add("L");
nestedList3.add("M");
nestedList3.add("N");
nestedList3.add("P");
nestedList3.add("P");
nestedList3.add("Q");
nestedList3.add("R");
nestedList3.add("S");
//list4
List<String>nestedList4 = new ArrayList<>();
nestedList4.add("T");
nestedList4.add("U");
nestedList4.add("V");
nestedList4.add("W");
//list5
List<String>nestedList5 = new ArrayList<>();
nestedList5.add("X");
//list6
List<String>nestedList6 = new ArrayList<>();
nestedList6.add("Y");
nestedList6.add("Z");
workflowList = new ArrayList<>();
workflowList.add(new Workflow("1",nestedList1));
workflowList.add(new Workflow("2",nestedList2));
workflowList.add(new Workflow("3",nestedList3));
workflowList.add(new Workflow("4",nestedList4));
workflowList.add(new Workflow("5",nestedList5));
workflowList.add(new Workflow("6",nestedList6));
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_item,menu);
MenuItem searchItem = menu.findItem(R.id.search_action);
if(searchItem!=null){
SearchView searchView = (SearchView) searchItem.getActionView(); //here stop working
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setQueryHint("Search Here!");
searchView.setIconified(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
workflowAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
notifyItemChanged()
workflowAdapter.getFilter().filter(newText);
return false;
}
});
}
super.onCreateOptionsMenu(menu, inflater);
}
}
//ParentAdapter
public class WorkflowAdapter extends RecyclerView.Adapter<WorkflowAdapter.WorkflowViewHolder> implements Filterable{
Context context;
List<Workflow> worflowArrayList;
List<Workflow> worflowArrayListFull;
private List<String>nestedlist = new ArrayList<>();
public WorkflowAdapter(Context context, List<Workflow> worflowArrayList) {
this.context = context;
this.worflowArrayListFull = worflowArrayList;
this.worflowArrayList = new ArrayList<>(worflowArrayListFull);
}
#NonNull
#Override
public WorkflowViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.general_list_item,parent,false);
return new WorkflowViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull WorkflowViewHolder holder, int parentPosition) {
//-get element from your dataset at this position
//-replace the contents of the view with that element
Workflow workflow = worflowArrayList.get(parentPosition);
holder.tvHeading.setText(workflow.getItemText());
//holder.titleImage.setImageResource(model.titleImage);
boolean isExpandable = workflow.isExpandable();
holder.expandableLayout.setVisibility(isExpandable ? View.VISIBLE:View.GONE);
if(isExpandable){
holder.mArrowImage.setImageResource(R.drawable.ic_baseline_arrow_upward_24);
}else{
holder.mArrowImage.setImageResource(R.drawable.ic_baseline_arrow_downward_24);
}
NestedAdapter childAdapter = new NestedAdapter(nestedlist);
holder.nestedRecyclerView.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));
holder.nestedRecyclerView.setHasFixedSize(true);
holder.nestedRecyclerView.setAdapter(childAdapter);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(holder.getAdapterPosition()){
case 1:
Toast.makeText(holder.itemView.getContext(), "Item 11 clicked. ", Toast.LENGTH_SHORT).show();
break;
}
workflow.setExpandable(!workflow.isExpandable());
nestedlist = workflow.getNestedList();
notifyItemChanged(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return worflowArrayList.size();
}
#Override
public Filter getFilter() {
return workflowFilter;
}
private final Filter workflowFilter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Workflow> filteredWorkflowList = new ArrayList<>();
if (constraint == null || constraint.length() == 0){
filteredWorkflowList.addAll(worflowArrayListFull);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for (Workflow workflow: worflowArrayListFull){
if(workflow.itemText.toLowerCase().contains(filterPattern))
filteredWorkflowList.add(workflow);
}
}
FilterResults results = new FilterResults();
results.values = filteredWorkflowList;
results.count = filteredWorkflowList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
worflowArrayList.clear();
worflowArrayList.addAll((ArrayList)results.values);
notifyDataSetChanged();
}
};
public static class WorkflowViewHolder extends RecyclerView.ViewHolder{
private TextView tvHeading;
private LinearLayout linearLayout;
private RelativeLayout expandableLayout;
private ImageView mArrowImage;
private RecyclerView nestedRecyclerView;
public WorkflowViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout=itemView.findViewById(R.id.linear_layout);
expandableLayout=itemView.findViewById(R.id.expandable_layout);
tvHeading = itemView.findViewById(R.id.tvHeading);
mArrowImage=itemView.findViewById(R.id.arro_imageview);
nestedRecyclerView = itemView.findViewById(R.id.child_rv);
}
}
}
//childAdapter
public class NestedAdapter extends RecyclerView.Adapter<com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder> {
private List<String> childItemList; /
public NestedAdapter(List<String> childItemList){
this.childItemList = childItemList;
}
#NonNull
#Override
public com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nested_item,parent,false);
return new com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull com.larntech.myassistant_java.workflow.NestedAdapter.NestedViewHolder holder, int childPosition) {
holder.mTv.setText(childItemList.get(childPosition));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(holder.getAdapterPosition()){
case 0:
DemoFragment demoFragment =new DemoFragment();
AppCompatActivity activity=(AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_workflow,demoFragment).addToBackStack(null).commit();
break;
case 1:
FragmentTwo fragmentTwo =new FragmentTwo();
AppCompatActivity activity2=(AppCompatActivity) view.getContext();
activity2.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_workflow,fragmentTwo).addToBackStack(null).commit();
break;
case 2:
Toast.makeText(holder.itemView.getContext(), "Item clicked. ", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
#Override
public int getItemCount() {
return childItemList.size();
}
public class NestedViewHolder extends RecyclerView.ViewHolder{
private TextView mTv;
public NestedViewHolder(#NonNull View itemView) {
super(itemView);
mTv=itemView.findViewById(R.id.nestedItemTv);
}
}
}

Update recyclerview data

since several days I try to handle data in recyclerview in viewpager2. The viewpager has an adapter managing the data in recyclerview. But everything I try to do seems to not work. Maybe I missundersteand the purpose or something. I hope you can help me.
This activity manages the viewpager and its adapter. It sends the data to the inner recyclerview:
public class AudioFilePanel extends AppCompatActivity
{
private String currentTab;
private ViewPagerAdapter adapter;
private ViewPager2 viewPager;
private TabLayout tabLayout;
private Map<String, List<String>> content;
private String path;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_file_panel);
viewPager = findViewById(R.id.view_pager2);
tabLayout = findViewById(R.id.tabs);
Button addFilesByTag = findViewById(R.id.add_files_with_tag);
if (null == currentTab)
{
currentTab = "music";
}
content = listByTag();
adapter = new ViewPagerAdapter(getApplicationContext(), new ArrayList<>(content.values()));
viewPager.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText(content.keySet().toArray()[position].toString())).attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
currentTab = tab.getText().toString();
}
#Override
public void onTabUnselected(TabLayout.Tab tab)
{
}
#Override
public void onTabReselected(TabLayout.Tab tab)
{
}
});
addFilesByTag.setOnClickListener(l ->
{
Intent fileBrowser = new Intent(AudioFilePanel.this, FileBrowser.class);
startActivityForResult(fileBrowser, 1);
});
}
private void updateViweData()
{
content = listByTag();
adapter = new ViewPagerAdapter(getApplicationContext(), new ArrayList<>(content.values()));
viewPager.setAdapter(adapter);
}
private Map<String, List<String>> listByTag()
{
Map<String, List<String>> result = new HashMap<>();
DirectoryDao dao = new DirectoryDao(getApplicationContext());
String[] categories = {"music", "ambience", "effect"};
for (String category : categories)
{
List<String> directories =
dao.getDirectoriesForCategory(category).stream().map(Directory::getPath).collect(Collectors.toList());
result.put(category, directories);
}
return result;
}
This is the view pager adapter. It takes the data directly from the activity and should trigger data update in the inner recyclerview every time when an item will be clicked. See line 118-128:
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder>
{
private List<List<String>> filesListsByCategory;
private LayoutInflater mInflater;
private Context ctx;
private ItemListAdapter adapter;
private List<String> categoryFiles;
public ViewPagerAdapter(Context context, List<List<String>> data)
{
this.mInflater = LayoutInflater.from(context);
this.filesListsByCategory = data;
this.ctx = context;
}
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType)
{
return new ViewHolder(mInflater.inflate(R.layout.item_viewpager, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
FileBrowserService fbs = new FileBrowserService();
categoryFiles = filesListsByCategory.get(position);
adapter = new ItemListAdapter(categoryFiles, new ItemList.OnListFragmentInteractionListener()
{
#Override
public void onListFragmentInteraction(String item)
{
categoryFiles = fbs.getFiles(categoryFiles.get(position));
categoryFiles.add(0, "previous directory");
updateUi(adapter, holder);
}
});
holder.myView.setAdapter(adapter);
}
private void updateUi(ItemListAdapter adapter, ViewHolder holder)
{
adapter.notifyDataSetChanged();
holder.myView.setAdapter(adapter);
}
#Override
public int getItemCount()
{
return filesListsByCategory.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
RecyclerView myView;
RelativeLayout relativeLayout;
ViewHolder(View itemView)
{
super(itemView);
myView = itemView.findViewById(R.id.my_list);
myView.setLayoutManager(new LinearLayoutManager(ctx));
relativeLayout = itemView.findViewById(R.id.container);
}
}
}
It is the adapter of inner recyclerview. It represents just a list of elements:
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ViewHolder>
{
private List<String> files;
private final OnListFragmentInteractionListener mListener;
public ItemListAdapter(List<String> items, OnListFragmentInteractionListener listener)
{
files = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_item, parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.file = files.get(position);
holder.mContentView.setText(files.get(position));
holder.mView.setOnClickListener(v ->
{
if (null != mListener)
{
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.file);
}
});
}
#Override
public int getItemCount()
{
return files.size();
}
class ViewHolder extends RecyclerView.ViewHolder
{
private final View mView;
private final TextView mContentView;
private String file;
private ViewHolder(View view)
{
super(view);
mView = view;
mContentView = view.findViewById(R.id.content);
}
}
}
The last thing is the ItemList fragment.
public class ItemList extends Fragment
{
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon screen orientation
* changes).
*/
public ItemList()
{
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static ItemList newInstance(int columnCount)
{
ItemList fragment = new ItemList();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener)
{
mListener = (OnListFragmentInteractionListener) context;
} else
{
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
if (view instanceof RecyclerView)
{
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1)
{
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else
{
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new ItemListAdapter(getArguments().getStringArrayList("list"), mListener));
}
return view;
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this fragment to allow an interaction in this
* fragment to be communicated to the activity and potentially other fragments contained in that activity.
* <p/>
* See the Android Training lesson
* <a href= "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener
{
// TODO: Update argument type and name
void onListFragmentInteraction(String item);
}
}
When I click, the data won't update. What I would like to have is:
This is what you have to do
add this method into your adapter class
public void updateData(List<String> filesList, int flag) {
if (flag == 0) { //append
for (int i = 0; i < filesList.size(); i++) {
files.add(messageList.get(i));
notifyItemInserted(getItemCount());
}
} else { //clear all
files.clear();
notifyDataSetChanged();
}
}
Then whenever you need to update recycle view call like below
mItemListAdapter.updateData(yourNewListOfItems, 0);
if you need to reset recycle-view call like below
mItemListAdapter.updateData(null, 1);
Add notifyDataSetChanged() in your adapter

I'm getting the same cardview images on my three tab layouts

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;
}
}

Update RecycleView from Fragment?

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

ViewPager.SimpleOnPageChangeListener Does Not Function

I have a ViewPager / PagerAdapter which should allow me to swipe through a series of footer images in order to change the station (by changing the string PLAYLIST):
...however when I swipe through the images - nothing seems to happen.
Any suggestions are greatly appreciated!
SOURCE:
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "EminemVEVO‎";
private OnPageChangeListener mPageChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
String PLAYLIST = "TimMcGrawVEVO‎";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
String PLAYLIST = "TimMcGrawVEVO‎";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
You're not adding the Listener to your Pager.
You need to call setOnPageChangeListener(mPageChangeListener) on your pagerAdapter.
For example in the Constructor:
public ImagePagerAdapter(){
super();
setOnPageChangeListener(mPageChangeListener);
}
for more info, check the docs. http://developer.android.com/reference/android/support/v4/view/ViewPager.html

Categories

Resources