TabbedActivity randomly shows fragments but is most of the time blank - java

I created a TabbedActivity with some fragments, these fragments sometimes load and sometimes they dont, i've searched everywhere but couldn't find the issue.
Example gif
This is my main activity:
public class TwitterActivity extends AppCompatActivity implements MessagesFragment.OnFragmentInteractionListener, NotificationFragment.OnFragmentInteractionListener,
ProfileFragment.OnFragmentInteractionListener, TimeLineFragment.OnFragmentInteractionListener {
private static final String APP_TAG = "Twitter";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.activity_twitter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final TextView toolbarTitle = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position == 0){
toolbarTitle.setText(R.string.tab_timeline);
}else if(position == 1){
toolbarTitle.setText(R.string.tab_messages);
}else if(position == 2){
toolbarTitle.setText(R.string.tab_notifications);
}else if(position == 3){
toolbarTitle.setText(R.string.tab_profile);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
});
tabLayout.setupWithViewPager(mViewPager, false);
}
#Override
public void onFragmentInteraction(Uri uri) { }
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(APP_TAG, String.valueOf(position));
if(position == 0){
return TimeLineFragment.newInstance();
}else if(position == 1){
return MessagesFragment.newInstance();
}else if(position == 2){
return NotificationFragment.newInstance();
}else if(position == 3){
return ProfileFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getString(R.string.tab_timeline);
case 1:
return getString(R.string.tab_messages);
case 2:
return getString(R.string.tab_notifications);
case 3:
return getString(R.string.tab_profile);
default:
return getString(R.string.tab_timeline);
}
}
}
}
This is one of my fragments (They are all the same):
public class TimeLineFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public TimeLineFragment() {
}
public static TimeLineFragment newInstance() {
TimeLineFragment fragment = new TimeLineFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_time_line, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#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 interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
This is my main activity's layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activities.TwitterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/tab_timeline"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_above="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Please help me
EDIT: removed the useless TabItems.

You may have to use getChildFragmentManager() instead of getSupportFragmentManager() as parameter to create you adapter.

Related

Toolbar text not showing when text is passed there

There was such problem: The text which I pass in SelectedActivity simply is not displayed. I have a DrawerLayout with fragments and on click on an element it goes to the SelectedActivity and loads the desired fragment. It works, but the SelectedActivity has a text of Toolbar. It's the one that doesn't show up. I'm new to programming and already completely confused. I would appreciate a solution! Here is my code:
SelectedActivity.java
public class SelectedActivity extends BaseActivity {
private static final String TAG = "SelectedActivity";
private static final String FRAGMENT_NAME = "fragment_name";
public MutableLiveData<String> toolBarTitle = new MutableLiveData<>();
TextView toolbarTitle;
public static void startActivityWithFragment(#NonNull Context context,
#NonNull Class<? extends Fragment> fragmentClass,
#Nullable Bundle bundle) {
context.startActivity(getStartIntent(context, fragmentClass, bundle));
}
private static Intent getStartIntent(#NonNull Context context,
#NonNull Class<? extends Fragment> fragmentClass,
#Nullable Bundle bundle) {
if (bundle == null) {
bundle = new Bundle();
}
bundle.putSerializable(FRAGMENT_NAME, fragmentClass);
Intent intent = new Intent(context, SelectedActivity.class);
intent.putExtras(bundle);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected);
Toolbar toolbar = findViewById(R.id.selected_activity_toolbar);
toolbarTitle = findViewById(R.id.selected_toolbar_title);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
Bundle extras = getIntent().getExtras();
if (extras == null) {
finish();
return;
}
Class<? extends Fragment> fragmentName = (Class<? extends Fragment>) extras.getSerializable(FRAGMENT_NAME);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_selected_activity, fragmentName, extras)
.commit();
toolBarTitle.observe(this, s -> {
if (s == null) return;
toolbarTitle.setText(s);
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void setToolBarTitle(String toolBarTitle){
try {
toolbarTitle.setText(toolBarTitle);
} catch (Exception e) {
e.printStackTrace();
}
}
}
ProfileFragment.java
public class ProfileFragment extends BaseFragment {
private FragmentProfileBinding binding;
public ProfileViewModel profileViewModel;
public View root;
SelectedActivity activity = new SelectedActivity();
public TextView textView;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
profileViewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
binding = FragmentProfileBinding.inflate(inflater, container, false);
textView = binding.textProfile;
profileViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
root = binding.getRoot();
binding.viewPager2.setAdapter(new ViewPagerAdapter(this));
binding.tabLayout.setTabIconTint(null);
new TabLayoutMediator(binding.tabLayout, binding.viewPager2,
(tab, position) -> {
if (position == 0) {
tab.setText(R.string.posts);
new PostsFragment();
} else {
tab.setText(R.string.saved);
new SavesFragment();
}
}).attach();
activity.setToolBarTitle(getString(R.string.menu_profile));
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onResume() {
super.onResume();
}
}
activity_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/selected_activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<TextView
android:id="#+id/selected_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:elevation="#dimen/dimen_10"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Selected Activity" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/container_selected_activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Fragments of view pager needs to be programmed from the main activity

I am using a view pager . I have three fragments in it I added a button in one of them and tried to make a method for it in the fragment class but this doesn't work. I tried after that to put the method in the main Activity class and it worked.
this is my MainActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myQuestions:
//newGame();
return true;
case R.id.aboutApp:
//showHelp();
return true;
case R.id.bestStudents:
//showHelp();
return true;
case R.id.myAccount:
//showHelp();
return true;
case R.id.signOut:
mAuth.signOut();
Intent i = new Intent(MainActivity.this, GeneralSignActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(tabPosition != 1){
mViewPager.setCurrentItem(1);
}
else{
this.finishAffinity();
System.exit(0);
}
}
}
and this is my fragment code :
public static LearnFragment newInstance(String param1, String param2) {
LearnFragment fragment = new LearnFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView=inflater.inflate(R.layout.fragment_learn,container,false);
return myView;
}
And this is the xml code of the main activity :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
and this is the fragment xml code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mk.playAndLearn.fragment.LearnFragment">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="click3"
android:text="click me"/>
</FrameLayout>
and tried to make a method for it in the fragment class but this
doesn't work
If you have added a Button to the Fragment, then you should initialize the Button inside the Fragment with the view prefix and adding the Button inside the Fragment layout too. So:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_learn,container,false);
Button myBtn = myView.findViewById(R.id.thebuttonid);
// use onClickListener here to handle the button
return myView;
}
I suppose you were handling the Button inside the MainActivity class which won't probably work.
You are handling the Button with onClick in the xml so, place the current code inside the Fragment and outside of onCreateView or any other methods:
public void click3(View v) {
switch(v.getId()) {
// do your stuff here
}
}

Manual swiping in view pager using Trinea/android-auto-scroll-view-pager is not working?

I am using third party library for automatic scrolling and touch events in an image slider every thing is working fine except manual swiping of images in image slider. I am not able to swipe images manually.
Name of the library which I am using is
"Trinea/android-auto-scroll-view-pager"
Here is my code for fragment where Ii am using auto scroll view pager:
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
TextView tv_slider, tv_button;
AutoScrollViewPager mViewPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
private static final Integer[] IMAGES= {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
private ArrayList<Integer> ImagesArray = new ArrayList<Integer>();
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
tv_slider=(TextView)v.findViewById(R.id.tv_slider);
tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
tv_button=(TextView)v.findViewById(R.id.tv_button);
tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));
for(int i=0;i<IMAGES.length;i++)
ImagesArray.add(IMAGES[i]);
mViewPager = (AutoScrollViewPager) v.findViewById(R.id.pager);
mViewPager.setAdapter(new SlidingImage_Adapter(getActivity(),ImagesArray));
mViewPager.setOffscreenPageLimit(1);
CirclePageIndicator indicator = (CirclePageIndicator)
v.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(3 * density);
NUM_PAGES =IMAGES.length;
mViewPager.startAutoScroll();
mViewPager.setInterval(3000);
mViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
Log.w("touched","down");
mViewPager.stopAutoScroll();
return true;
//break;
case MotionEvent.ACTION_UP:
Log.w("touched","up");
mViewPager.startAutoScroll();
return true;
}
return true;
}
});
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
switch (pos){
case 0:
tv_slider.setText(getString(R.string.es_content));
break;
case 1:
tv_slider.setText(getString(R.string.dm_content));
break;
case 2:
tv_slider.setText(getString(R.string.ev_content));
break;
case 3:
tv_slider.setText(getString(R.string.it_content));
break;
case 4:
tv_slider.setText(getString(R.string.md_content));
break;
case 5:
tv_slider.setText(getString(R.string.seo_content));
break;
case 6:
tv_slider.setText(getString(R.string.sd_content));
break;
case 7:
tv_slider.setText(getString(R.string.wd_content));
break;
}
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
mViewPager.startAutoScroll();
}
#Override
public void onStop() {
super.onStop();
mViewPager.stopAutoScroll();
}
}
This is my adapter class:
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
super();
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.sliding_images, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
This is homefragment.xml file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/background"
tools:context="com.vamediabox.vamediaboxapp.activities.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/colorPrimary">
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/rl_slider"
android:gravity="center_horizontal"
app:cardUseCompatPadding="true"
app:cardElevation="4dp"
app:cardCornerRadius="3dp"
app:cardPreventCornerOverlap="false"
android:layout_centerHorizontal="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="2dp"
android:id="#+id/rl1">
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_margin="2dp"
android:layout_alignParentTop="true" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/pager"
android:padding="5dip"
app:centered="true"
app:fillColor="#color/colorPrimary"
app:pageColor="#color/view_color"
app:snap="false" />
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/tv_slider"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:textSize="14sp"
android:layout_below="#+id/indicator"
android:textColor="#color/slider_text"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
and last this is sliding_images.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY" />
</FrameLayout>
not sure if you still looking for a way to fix this in case you do, check consumeTouch inside AutoScrollViewPager this is where your issue is.
You need to make sure that
getParent().requestDisallowInterceptTouchEvent(true)
is getting called.
hope this helps.
Cheers

TabItem icons disappeared after using ViewPager

My TabLayout was perfect, showing with icons, and then I had to add a ViewPagerOnTabSelectedListener, and my icons are missing.
Can someone help me please?
I have tried solutions like adding this in my MainActivity, but nothing changed:
tabLayout.getTabAt(0).setIcon(R.drawable.home);
This is my code:
public class MainActivity extends AppCompatActivity {
private ViewPager pager;
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.pager);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigation);
TabLayout tabLayout = new TabLayout(this);
tabLayout = (TabLayout) findViewById(R.id.toolbar);
tabLayout.setupWithViewPager(pager);
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(pager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
pager.setCurrentItem(tab.getPosition());
Log.i("TAG", "onTabSelected: " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
final PagerAdapter mAdapter = new MainPagerAdapter(getSupportFragmentManager());
pager.setAdapter(mAdapter);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_adresse:
pager.setCurrentItem(0);
return true;
case R.id.navigation_cognitif:
pager.setCurrentItem(1);
return true;
case R.id.navigation_deplacement:
pager.setCurrentItem(2);
return true;
case R.id.navigation_yeux:
pager.setCurrentItem(3);
return true;
}
return false;
}
});
}
class MainPagerAdapter extends FragmentPagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MeFragment();
case 1:
return new MeFragment();
case 2:
return new MeFragment();
case 3:
default:
return new MeFragment();
}
}
#Override
public int getCount() {
return 4;
}
}
Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.blabla.bloublou.MainActivity"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="?attr/colorPrimary">
<android.support.design.widget.TabItem
android:id="#+id/home_button"
android:icon="#drawable/home"
android:title="home"/>
<android.support.design.widget.TabItem
android:id="#+id/me_button"
android:icon="#drawable/me"
android:title="moi" />
<android.support.design.widget.TabItem
android:id="#+id/configuration_button"
android:icon="#drawable/tools"
android:title="configuration"
/>
<android.support.design.widget.TabItem
android:id="#+id/help_button"
android:icon="#drawable/help"
android:title="aide"/>
</android.support.design.widget.TabLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:background="#color/colorPrimary"
app:itemIconTint="#color/icon"
app:itemTextColor="#color/icon"
app:menu="#menu/navigation">
</android.support.design.widget.BottomNavigationView>
<com.umanit.emfsc.NonSwipeableViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/navigation"
android:layout_below="#+id/toolbar"
/>
<include layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"
android:layout_above="#id/navigation"
/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
tabLayout.setupWithViewPager(pager);
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(pager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
pager.setCurrentItem(tab.getPosition());
Log.i("TAG", "onTabSelected: " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
final PagerAdapter mAdapter = new MainPagerAdapter(getSupportFragmentManager());
pager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(pager);
make above changes,the problem is you are setting the viewpager before pager has set the adapter,let me know if this won't work.

tabIndicator is not showing up properly(it is showing in the reverse way)

I have added tab layout in my activity.Everything is working fine, but the tab Indicators are not showing up as expected. I am adding the photo below so that you can get an idea.I mean to say that when I click on Overview(tab indicator is shown below Detail fragment) and vice versa.
Given below is the XML code(Activity_inventory_detail):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_inventory_detail_"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.github.fafaldo.fabtoolbar.widget.FABToolbarLayout
android:id="#+id/fabtoolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:containerId="#+id/fabtoolbar_container"
app:fabId="#+id/fabtoolbar_fab"
app:fabToolbarId="#+id/fabtoolbar_toolbar"
app:fadeInFraction="0.2"
app:hideDuration="200"
app:horizontalMargin="16dp"
app:showDuration="600"
app:verticalMargin="16dp">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabIndicatorColor="#color/white"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#color/white" />
<com.aaryanapps.hub.ui.controls.LockableViewPager
android:id="#+id/pager_inventory_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tab_layout"
android:background="#color/white"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<RelativeLayout
android:id="#+id/fabtoolbar_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabtoolbar_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/abc_ic_menu_share_mtrl_alpha"
app:backgroundTint="#color/colorPrimary"
app:fabSize="mini" />
</RelativeLayout>
<LinearLayout
android:id="#+id/fabtoolbar_toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
app:backgroundTint="#color/colorPrimary">
<ImageView
android:id="#+id/one"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="centerInside"
android:src="#drawable/abc_ic_menu_share_mtrl_alpha" />
<ImageView
android:id="#+id/two"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:scaleType="centerInside"
android:src="#drawable/ic_menu_gallery_white" />
<ImageView
android:id="#+id/three"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:backgroundTint="#color/tranperent_white"
android:scaleType="centerInside"
android:src="#drawable/ic_menu_camera_white" />
</LinearLayout>
</com.github.fafaldo.fabtoolbar.widget.FABToolbarLayout>
</RelativeLayout>
Java Code(Inventory_deatil_Activity.java) is given below(can not post full code as it is having many lines), only adding Tablayout and the related part. This is code in which I declared the Tablayout .
public class Inventory_detail_Activity extends AbstractKActivity implements DetailsDataListener, View.OnClickListener,
SimpleGestureFilter.SimpleGestureListener,
ContentManager.PickContentListener {
public static final String TAG_LABEL_OVERVIEW = "Overview";
public static final String TAG_LABEL_DETAILS = "Detail";
InventoryItemsList inventoryItems;
protected int current_item_index = 0;
public List<InventoryItem> inventory_items_list = new ArrayList<>();
InventoryItem inventory_item;
private ViewPager viewPager;
private ViewPagerAdapter pagerAdapter;
TabLayout tabLayout;
this is where I have initialized the Tablayout .
protected void init() {
final TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.pager_inventory_detail);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Given below is the code for ViewPagerAdapter
class ViewPagerAdapter extends SmartFragmentStatePagerAdapter<ItemDetailAbstractFragment> {
//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) {
ItemDetailAbstractFragment caf;
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
caf = new ItemDetailOverviewFragment();
break;
case 1: // Fragment # 0 - This will show FirstFragment different title
caf = new ItemDetailDetailsFragment();
break;
default:
return null;
}
Bundle args = ActivityStateManager.getInstance().getActivityState(getLocalClassName());
if (args == null) {
args = new Bundle();
}
caf.setFlowItem(inventory_item);
if(current_item_index == -1) {
caf.setFlowItem(inventory_item);
caf.populateData();
}
return caf;
}
#Override
public int getCount() {
return 2;
}
public void addFragment(int position, String title) {
mFragmentTitleList.add(position, title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onPause() {
Log.e("DEBUG", "onPause of ClientListTabactivity");
super.onPause();
// currentState.putSerializable("flowItem",inventory_item);
// ActivityStateManager.getInstance().updateActivityState(getLocalClassName(), currentState);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// outState.putSerializable("flowItem",inventory_item);
// ActivityStateManager.getInstance().updateActivityState(getLocalClassName(), outState);
contentManager.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
contentManager.onRestoreInstanceState(savedInstanceState);
}
private void setupViewPager(ViewPager viewPager) {
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(0, TAG_LABEL_OVERVIEW);
pagerAdapter.addFragment(1, TAG_LABEL_DETAILS);
viewPager.setAdapter(pagerAdapter);
//updateFragmentsForFlowItem();
}
[Edited]:
this is the AbstractActivity code:
public class AbstractKActivity extends AppCompatActivity {
protected int content_view = 0;
protected String mTitle = "";
protected TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prepareInit();
if (content_view != 0) {
setContentView(content_view);
}
initToolbar();
processIntent();
init();
}
protected void initToolbar() {
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_actionbar);
title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText(mTitle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setTitle(mTitle);
}
protected void processIntent() {
}
protected void init() {
}
protected void prepareInit() {
}
protected void setToolbarTitleText(String titleText) {
mTitle = titleText;
title.setText(titleText);
}
}
At first Modify your CODE. Don't return null; . You should return your Default Fragment .
Don't
case 1: // Fragment # 0 - This will show FirstFragment different title
caf = new ItemDetailDetailsFragment();
break;
default:
return null;
Do
#Override
public Fragment getItem(int position) {
ItemDetailAbstractFragment caf;
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
caf = new ItemDetailOverviewFragment();
break;
case 1: // Fragment # 0 - This will show FirstFragment different title
caf = new ItemDetailDetailsFragment();
break;
default:
return new ItemDetailOverviewFragment();
}
Secondly
viewPager = (ViewPager) findViewById(R.id.pager_inventory_detail);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0); // Declare this
EDIT
public void onTabSelected(TabLayout.Tab tab) {
tab.select();
}

Categories

Resources