I can not implement a data update of a Viewpager based fragment.
In fact I have a service that verifies and retrieves the latest information updates published online and comes to feed my database.
Once the job is finished I should update the screen but that's where I'm stuck.
I tried many techniques but until then I have not yet received to update the screen.
I am so overwhelmed by the subject that I do not have the right words.
Thanks for your help
My main activity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "MainActivity";
ViewPager viewPager;
TabLayout tabLayout;
DrawerLayout drawer;
NavigationView navigationView;
ActionBarDrawerToggle toggle;
Context mContext;
PagerAdapter vAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mContext = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
reloadData();
}
private void setupViewPager(ViewPager viewPager) {
vAdapter = new PagerAdapter(getSupportFragmentManager());
vAdapter.addFragment(new StartFragment(), "START");
vAdapter.addFragment(new MapFragment(), "MAP");
vAdapter.addFragment(new ListArticle(), "ARTICLES");
viewPager.setAdapter(vAdapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_profile:
startActivity(new Intent(mContext, ProfileActivity.class));
break;
case R.id.nav_map:
startActivity(new Intent(mContext, MapActivity.class));
break;
case R.id.nav_history:
startActivity(new Intent(mContext, HistoryActivity.class));
break;
case R.id.nav_help:
break;
default:
return false;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void scheduleJobMatchDataUpdate(){
JobScheduler jobScheduler = (JobScheduler)getApplicationContext()
.getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(this,
MatchUpdatedJob.class);
JobInfo jobInfo = null;
//if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
jobInfo = new JobInfo.Builder(1, componentName)
.setPeriodic(60000).setRequiredNetworkType(
JobInfo.NETWORK_TYPE_NOT_ROAMING)
.setPersisted(true).build();
// }
jobScheduler.schedule(jobInfo);
}
public void reloadData() {
scheduleJobMatchDataUpdate();
StartFragment fragment = new StartFragment();
if (fragment.isInLayout()) {
fragment.data();
}
}
}
//My PagerAdapter
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public class StartFragment extends Fragment implements ArticleAdapter.ClickCB,
BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener{
static final String TAG = "StartFragment";
public StartFragment() {
// Let empty
}
LinearLayoutManager mLayoutManager;
private SwipeRefreshLayout srl;
ArticleAdapter mAdapter;
Context mContext;
List<Article> mList;
List<Article> mListSelected = new ArrayList<>();
Call<List<Article>> call;
ApiService service;
RecyclerView rcv;
Bundle bundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = getActivity();
this.mList = Article.findAll(this.mContext);
this.bundle = savedInstanceState;
service = RetrofitBuilder.createService(ApiService.class);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_start, container, false);
SliderLayout mSlider = (SliderLayout) view.findViewById(R.id.slider);
String[] imgUrl = new String[3];
imgUrl[0] = "http://...1.jpg";
imgUrl[1] = "http://...2.jpg";
imgUrl[2] = "http://...3.jpg";
for (String s: imgUrl){
MatchSliderView sliderView = new MatchSliderView(getContext());
sliderView
.image(s)
.description("...")
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
sliderView.bundle(new Bundle());
sliderView.getBundle()
.putString("extra",s);
mSlider.addSlider(sliderView);
}
mSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
// mSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mSlider.setCustomAnimation(new DescriptionAnimation());
mSlider.setDuration(5000);
mSlider.addOnPageChangeListener(this);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
mLayoutManager = new LinearLayoutManager(MainApplication.getContext());
mLayoutManager.setOrientation(1);
rcv.setLayoutManager(mLayoutManager);
rcv.setHasFixedSize(true);
//mList = Article.findAll(this.mContext);
this.mAdapter = new ArticleAdapter(this.mContext,
StartFragment.this, mList, mListSelected);
rcv.setItemViewCacheSize(mList.size());
rcv.setAdapter(this.mAdapter);
Flubber.with()
.animation(Flubber.AnimationPreset.FADE_IN_UP)
.repeatCount(1)
.duration(2000)
.createFor(rcv)
.start();
srl = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefreshLayout);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
onItemsLoadComplete();
}
});
return view;
}
void onItemsLoadComplete() {
loadData();
srl.setRefreshing(false);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onSliderClick(BaseSliderView slider) {
Toast.makeText(mContext, slider.getmTitle(),
Toast.LENGTH_SHORT).show();
}
#Override
public void removeNotify(Selection selection) {
badgeView.decrement();
}
public void loadData(){
try{
call = service.matchs();
call.enqueue(new Callback<List<Article>>() {
#Override
public void onResponse(Call<List<Article>> call, Response<List<Article>> response) {
if(response.isSuccessful()){
Article.deleteAll(mContext);
Article.saveAll(mContext,response.body());
}else{
Toast.makeText(mContext, "Update failed!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<List<Article>> call, Throwable t) {
call.isCanceled();
t.printStackTrace();
}
});
}catch (Exception e){
e.printStackTrace();
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void refreshData(){
mList.clear();
mList.addAll(Article.findAll(this.mContext));
mAdapter.swap((ArrayList<Article>)mList);
}
#Override
public void onPause() {
super.onPause();
if (srl!=null) {
srl.setRefreshing(false);
srl.destroyDrawingCache();
srl.clearAnimation();
}
}
}
public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> implements Filterable {
private Context mContext;
private static final String LOG_TAG = ArticleAdapter.class.getSimpleName();
List<Article> mListArticles = new ArrayList<>();
private List<Article> articleList;
private List<Article> articleListFiltered;
private ArticlesAdapterListener listener;
public ArticleAdapter(Context context, List<Article> mListItems){
this.mContext = context;
//this.mListArticles = mListItems;
if (mListArticles != null) {
mListArticles.clear();
mListArticles.addAll(mListItems);
}
else {
this.mListArticles = mListItems;
}
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article, parent, false);
return new ViewHolder(mContext, mListArticles, view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Article item = mListArticles.get(position);
holder.title.setText(Html.fromHtml( " " + item.getTitre()));
//Glide.with(this).load(item.getMedia()).into((ImageView) findViewById(R.id.media));
if(item.getMedia() != null && item.getMedia().length() >10) {
Picasso.with(mContext).load(item.getMedia()).into(holder.img);
}
}
#Override
public int getItemCount() {
return mListArticles.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
articleListFiltered = articleList;
} else {
List<Article> filteredList = new ArrayList<>();
for (Article row : articleList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getTitre().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
articleListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = articleListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
articleListFiltered = (ArrayList<Article>) results.values;
notifyDataSetChanged();
}
};
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private Context mContext;
private List<Article> mItems;
public TextView title;
public ImageView img;
public ViewHolder(Context context, List<Article> newsList, View view){
super(view);
this.mContext = context;
this.mItems = newsList;
this.title= (TextView)view.findViewById(R.id.title);
this.img= (ImageView) view.findViewById(R.id.media);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticleDetailActivity.class);
intent.putExtra("id", mItems.get(getAdapterPosition()).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
}
}
public interface ArticlesAdapterListener {
void onArticleSelected(Article article);
}
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
mAdapter.swap((ArrayList<Article>)mList);
mAdapter.notifyDataSetChanged();
Related
I am using RecycleView to display list of Name and Description. I am using Fragment to view the desired layout. Now, I want to open new Activity onItemClick. I have declared SetOnItemClickListener inside the Fragment, i.e. in "View onCreateView". But it is not working. Here is my code:
This is my java class:
public class TabsHeaderActivity extends AppCompatActivity {
private static final String TAG = TabsHeaderActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_header);
final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) getSupportActionBar().setTitle("TECHNOLOGY");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.setupWithViewPager(viewPager);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
int vibrantColor = palette.getVibrantColor(R.color.primary_500);
int vibrantDarkColor = palette.getDarkVibrantColor(R.color.primary_700);
collapsingToolbarLayout.setContentScrimColor(vibrantColor);
collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
}
});
} catch (Exception e) {
// if Bitmap fetch fails, fallback to primary colors
Log.e(TAG, "onCreate: failed to create bitmap from background", e.fillInStackTrace());
collapsingToolbarLayout.setContentScrimColor(
ContextCompat.getColor(this, R.color.primary_500)
);
collapsingToolbarLayout.setStatusBarScrimColor(
ContextCompat.getColor(this, R.color.primary_700)
);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
Log.d(TAG, "onTabSelected: pos: " + tab.getPosition());
switch (tab.getPosition()) {
case 0:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.cyan_50)), "Cyan");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.amber_50)), "Amber");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.purple_50)), "Purple");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.grey)), "Grey");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem searchItem = menu.findItem(R.id.menuSearch);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private 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);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public static class DummyFragment extends Fragment {
int color;
Intent intent;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
#Override
public void onItemClick(View view, int position) {
switch (position) {
case 3:
intent = new Intent(view.getContext(), LaunchScreenActivity.class);
startActivity(intent);
}
}
});
return view;
}
}
}
This is my Adapter class:
public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
OnItemClickListener clickListener;
private Context context;
public DessertAdapter(Context context) {
this.context = context;
desserts = Dessert.prepareDesserts(
context.getResources().getStringArray(R.array.dessert_names),
context.getResources().getStringArray(R.array.dessert_descriptions));
}
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
}
#Override
public int getItemCount() {
return desserts == null ? 0 : desserts.size();
}
public class DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView mName;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(v, getPosition());
}
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
I am not sure what I am doing wrong. I have checked it in debugger mode. I have put a breakpoint at line:
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
Now, when my Activity is loading debugger comes on this line but, doesn't go inside it. But, when I am clicking something, the debugger doesn't even come on this line, means when I am clicking an item, SetOnItemClickListener doesn't get triggered.
My xml code is:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_light">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin" />
</FrameLayout>
Well, you implemented a normal click listener
DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener
But you never set it.
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
Did you forget about itemView.setOnClickListener(this)?
I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}
I've a viewpager looping a multiple fragments and set in a viewpager. Each fragment has a listview with checkbox. On clicking any one item of a list it will notify all the fragments so that all checkbox remains unchecked and only clicked item will be checked.
CreateGroupStep1
public class CreateGroupStep1 extends BaseActivity implements IGroup {
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView next_btn,back;
private int current_item_position;
private ViewPagerAdapter adapter;
private ArrayList<Interest> interestList;
ArrayList<String>al_sports;
ArrayList<String>al_list_collect;
private ArrayList<String>al_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group_step1);
storeDataOfArrayList();
al_list_collect=new ArrayList<String>();
initViews();
}
public void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
RelativeLayout back=(RelativeLayout) findViewById(R.id.back);
back=(RelativeLayout) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
next_btn=(ImageView) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent ii=new Intent(CreateGroupStep1.this,CreateGroupStep2.class);
//startActivity(ii);
Toast.makeText(CreateGroupStep1.this, "", Toast.LENGTH_SHORT).show();
}
});
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(CreateGroupStep1.this.getSupportFragmentManager());
for (int i=0;i<al_title.size();i++)
{
adapter.addFragment(InterestFragmentForGroup.getInstance(al_sports),al_title.get(i));
viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
current_item_position = position;
// Toast.makeText(CreateGroupStep1.this, "scrolled", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClickedNextButton(final String message) {
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CreateGroupStep1.this,message, Toast.LENGTH_SHORT).show();
}
});
}
public 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);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void storeDataOfArrayList()
{
saveData();
al_sports=new ArrayList<>();
al_sports.add("Baseball");
al_sports.add("Basketball");
al_sports.add("Bowling");
al_sports.add("Cricket");
al_sports.add("Football");
al_sports.add("Golf");
al_sports.add("Handball");
al_sports.add("Hockey");
al_sports.add("Jogging");
al_sports.add("Racquetball");
al_sports.add("Running");
al_sports.add("Skiing");
al_sports.add("Snowboarding");
al_sports.add("Soccer");
al_sports.add("Swimming");
al_sports.add("Tennis");
}
private void saveData()
{
al_title=new ArrayList<String>();
al_title.add("Sports");
al_title.add("LifeStyle");
al_title.add("Adventure");
al_title.add("Recreation");
al_title.add("The Arts");
al_title.add("College");
al_title.add("Sos");
al_title.add("Industry");
al_title.add("LocalBiz");
al_title.add("Corporate");
}
}
InterestAdapterForGroup
public class InterestAdapterForGroup extends RecyclerView.Adapter<InterestAdapterForGroup.MyViewHolder> implements IGroup {
public int selectedPosition = -1;
IGroup inter;
private LayoutInflater inflater;
private ArrayList<Interest> stList;
private Context mContext;
private ArrayList<Interest> checked_item = new ArrayList<>();
public InterestAdapterForGroup(Context context, ArrayList<Interest> al_list) {
this.mContext = context;
this.stList = al_list;
inflater = LayoutInflater.from(context);
inter = (IGroup) mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_ethnic, parent, false);
InterestAdapterForGroup.MyViewHolder holder = new InterestAdapterForGroup.MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final int pos = position;
final Interest interest = stList.get(position);
holder.title.setText(interest.getName());
if (position == selectedPosition) {
holder.chkSelected.setChecked(true);
} else {
holder.chkSelected.setChecked(false);
}
holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
interest.isSelected = isChecked;
if (isChecked) {
checked_item.clear();
checked_item.add(interest);
selectedPosition = position;
} else {
checked_item.remove(interest);
selectedPosition = -1;
}
notifyDataSetChanged();
}
}
});
clickedItems();
}
public void clickedItems() {
if (checked_item.size() > 0) {
if (Constants.GLOBAL_ARRAY.size() > 0) {
Constants.GLOBAL_ARRAY.clear();
for (int i = 0; i < checked_item.size(); i++) {
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
}
}
ArrayList<String> al_name = new ArrayList<String>();
ArrayList<String> al_nam = new ArrayList<String>();
for (int i = 0; i < checked_item.size(); i++) {
al_name.add(checked_item.get(i).getEmailId());
}
for (int i = 0; i < checked_item.size(); i++) {
al_nam.add(checked_item.get(i).getName());
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
inter.onClickedNextButton(al_nam.toString());
}
public ArrayList<Interest> getCheckedItemList() {
return stList;
}
#Override
public int getItemCount() {
return stList.size();
}
#Override
public void onClickedNextButton(String message) {
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CheckBox chkSelected;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_ethnic);
chkSelected = (CheckBox) itemView
.findViewById(R.id.chk);
}
#Override
public void onClick(View v) {
}
}
}
InterestFragmentForGroup
public class InterestFragmentForGroup extends BasePagerFragment implements IPager {
private ArrayList<String> interestList;
private ArrayList<Interest> interestListfunction;
public static Fragment getInstance(ArrayList<String> interestList){
Bundle bundle = new Bundle();
bundle.putSerializable("interestList",interestList);
InterestFragmentForGroup interestsFragment = new InterestFragmentForGroup();
interestsFragment.setArguments(bundle);
return interestsFragment;
}
public void getInterestList(){
interestList = (ArrayList<String>) getArguments().getSerializable("interestList");
}
private RecyclerView recyclerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sports_fragment, container, false);
initViews(rootView);
return rootView;
}
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);
getInterestList();
setData();
}
public void setData() {
interestListfunction = new ArrayList<>();
for (int i = 0; i < interestList.size(); i++) {
Interest st = new Interest(interestList.get(i), interestList.get(i), false);
interestListfunction.add(st);
}
adapter2 = new InterestAdapterForGroup(getActivity(), interestListfunction);
recyclerView.addItemDecoration(new DividerDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter2);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
}
}
I am using ViewPager inside my Navigation Drawer all are works fine in devices other than marshmallow devices. in marshmallow devices when i clicking toggle button or swiping the navigation drawer (in both direction) feel a stuck(glitch) in the flow, also when i swipe the viewpager into different tabs also found the stuckking. This was found only in marshmallow device. please help me,, thanks in advance....
this is my code
activity class
public class HomeActivity extends AppCompatActivity{
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
}
return true;
}
});
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
}
ViewPager fragment
public class HomeViewPagerFragment extends Fragment {
ArrayList<Model> mArrayList= new ArrayList<>();
Model model;
TabLayout tabLayout;
ViewPager viewPager;
HomeViewPagerAdapter viewPagerAdapter;
public HomeViewPagerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_view_pager,container,false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
// parsing and add datas into mArrayList
viewPagerAdapter = new HomeViewPagerAdapter(getActivity().getSupportFragmentManager(),mArrayList);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
viewPager.setCurrentItem(Credentials.homeTabSelected);
tabLayout = (TabLayout)rootView.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
Credentials.homeTabSelected = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootView;
}
}
viewpager adapter
public class HomeViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Model> mArrayList = new ArrayList<>();
String tabTitles[] = new String[] { "tab1","tab2" };
public HomeViewPagerAdapter(FragmentManager fm, ArrayList<Model> arrayList) {
super(fm);
mArrayList = arrayList;
}
#Override
public Fragment getItem(int position) {
if(position==0) {
return new HomeCentralFragment();
}
else {
return HomeRecyclerFragment.newInstance(mArrayList);
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
HomeCentralFragment
public class HomeCentralFragment extends Fragment {
public HomeCentralFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_central,null);
//my code is here(buttons, click events etc...)
return rootView;
}
}
HomeRecyclerFragment
public class HomeRecyclerFragment extends Fragment {
RecyclerView recyclerView;
public static ArrayList<Model> mArrayList =new ArrayList<>();
Fragment fragment;
FragmentTransaction fragmentTransaction;
public static HomeRecyclerFragment newInstance(ArrayList<Model> arrayList){
HomeRecyclerFragment fragment = new HomeRecyclerFragment();
mArrayList = arrayList;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_recycler_view,null);
recyclerView = (RecyclerView)rootView.findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
//to make horizontal or vertical listview using recyclerview
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new HomeRecyclerAdapter(getActivity(), mArrayList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)) {
Credentials.selectedPolititian = rv.getChildAdapterPosition(child);
Intent intent = new Intent(getContext(), PersonDetailActivity.class);
intent.putExtra("Class","HomeActivity");
intent.putExtra("array",mArrayList);
startActivity(intent);
getActivity().finish();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
return rootView;
}
}
HomeRecyclerAdapter
public class HomeRecyclerAdapter extends RecyclerView.Adapter<HomeRecyclerAdapter.ViewHolder> {
private ArrayList<Model> profiles;
Context mContext;
public HomeRecyclerAdapter(Context context, ArrayList<Model> profile) {
this.profiles = profile;
this.mContext = context;
}
#Override
public HomeRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_fragment_home_recycler, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HomeRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(profiles.get(i).getmName());
int length= profiles.get(i).getmDepartment().size();
int k;
String res ="";
for (k=0;k<length;k++){
res = res + profiles.get(i).getmDepartment().get(k)+"\n";
}
viewHolder.department.setText(res);
}
#Override
public int getItemCount() {
return profiles.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name, department;
//private ImageView imageView;
public ViewHolder(View view) {
super(view);
// imageView = (ImageView) view.findViewById(R.id.image);
name = (TextView) view.findViewById(R.id.p_name);
department = (TextView) view.findViewById(R.id.p_department);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
});
}
}
}
check view fragments layout, avoid .jpeg images (use .png images)...
check the view pager with some simple fragments, if it work smoothly check the layout views..
I spend time to search an answer to my problem without success.
When i rotating my fragments are recreated inside viewpager adapter but not displayed, i don't no why ?
I have tried FragmentPagerStateAdapter instead of FragmentPagerAdapter but it doesn't work.
My activity code :
public class BookingsActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener,LoginDialogFragment.LoginDialogFragmentListener, BookingsFragment.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
.....
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(BookingsFragment.newInstance(), "A venir");
adapter.addFragment(BookingsFragment.newInstance(), "Terminées");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<BookingsFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public BookingsFragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(BookingsFragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
My fragment code :
public class BookingsFragment extends Fragment {
private ArrayList<Bookings> mBookings = new ArrayList<>();
private BookingCardAdapter adapter;
private RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
private OnFragmentInteractionListener mListener;
private Location mLastLocation;
public BookingsFragment() {
// Required empty public constructor
}
public static BookingsFragment newInstance() {
BookingsFragment fragment = new BookingsFragment();
// Supply index input as an argument.
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bookings, container, false);
// Inflate the layout for this fragment
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(this.getContext());
recyclerView.setLayoutManager(mLayoutManager);
adapter = new BookingCardAdapter(mBookings, this.getContext(), new BookingCardAdapter.BookingCardAdapterSubmitListener() {
#Override
public void onBookingClick(Bookings booking, int state) {
handleBookingClick(booking,state);
}
});
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void setBookings(ArrayList<Bookings> bookings, int page) {
if (bookings != null && bookings.size() > 0) {
if (adapter != null) {
if (page == 1) {
mBookings.clear();
}
for (Bookings b : bookings) {
mBookings.add(b);
}
adapter.notifyDataSetChanged();
}
}
}
public void setLocation(Location location) {
if (location!=null) {
mLastLocation=location;
}
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}