I have ViewPager2 with 3 Fragments and all has recyclerview but in Middle fragment recyclerview not scrolling if i try to touch recyclerview Items but it scroll smoothly if i touch right or left side of recycler as you can see in image.
View Pager Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabItemes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="center"
android:clipToPadding="true"
app:tabPaddingBottom="0dp"
app:tabPaddingEnd="0dp"
app:tabPaddingStart="0dp"
app:tabPaddingTop="0dp"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed"
app:tabTextColor="#color/black"
app:tabSelectedTextColor="#color/primary"
app:tabIndicatorColor="#color/primary_light">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="About" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Media" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connections" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/profileViewPager"
android:orientation="horizontal"
android:nestedScrollingEnabled="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ViewPager2 Setup
userInfo_ViewPager = view.findViewById(R.id.profileViewPager);
userInfo_ViewPager.setOffscreenPageLimit(1);
userProfile_tabAdapter = new UserProfile_TabAdapter(getChildFragmentManager(), getLifecycle());
TabLayout tabLayout = view.findViewById(R.id.tabItemes);
Media Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true"
android:nestedScrollingEnabled="true"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<TextView
android:id="#+id/seeAllPhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:textSize="12sp"
android:textStyle="bold"
android:text="See All"
/>
<com.elaxer.CustomClass.RotateLoading
android:id="#+id/rotateloading"
android:layout_width="80dp"
android:layout_height="80dp"
app:loading_color="#color/greenElaxer"
android:layout_gravity="center_horizontal|center_vertical"
app:loading_speed="11"
app:loading_width="5dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/userPhotos_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingEnd="10dp"
android:paddingStart="10dp"
tools:listitem="#layout/recycler_view_item_8"
tools:spanCount="5"
tools:layoutManager="GridLayoutManager" />
</LinearLayout>
Media Fragment
public class UserPhoto_fragment extends Fragment {
RecyclerView photosRecycler;
StaggeredGridLayoutManager layoutManager;
List<UserGrid> ImageList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.userprofile_photos,container,false);
photosRecycler=view.findViewById(R.id.userPhotos_recycler);
seeAllPhotos = view.findViewById(R.id.seeAllPhotos);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
ImageList=new ArrayList<>();
photosRecycler.addItemDecoration(new SpacesItemDecoration(16));
photosRecycler.setLayoutManager(layoutManager);
photosRecycler.setHasFixedSize(true);
adapter=new fetchPhoto_Adapter();
photosRecycler.setAdapter(adapter);
return view;
}
public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{
#NonNull
#Override
public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.userprofile_photogallery,viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
UserGrid userImages = ImageList.get(i);
Glide.with(getActivity()).load(userImages.getWeb_URL()).into(viewHolder.image);
}
#Override
public int getItemCount() {
if (ImageList!=null && ImageList.size()>0){
return ImageList.size();
}else {
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.UserProfile_photoThumb);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
image.setClipToOutline(true);
}
}
}
}
private final RecyclerView.OnItemTouchListener itemTouchListener = new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
int action = e.getAction();
Log.d(TAG, "onInterceptTouchEvent: "+action);
if (photosRecycler.canScrollVertically(1)){
if (action == MotionEvent.ACTION_MOVE){
photosRecycler.requestDisallowInterceptTouchEvent(true);
}
return false;
}else {
if (action == MotionEvent.ACTION_MOVE){
photosRecycler.requestDisallowInterceptTouchEvent(false);
photosRecycler.removeOnItemTouchListener(this);
}
return true;
}
}
#Override
public void onTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
};
}
What i have already tried:
Nested ScrollView Enable/Disable in Recyclerview and Viewpager
RecyclerView.OnItemTouchListener Implementation to get recyclerview focus
Changed Fragment layout to constraintlayout.
I am running out of ideas and google search for solution. Can you suggest why my recyclerview is not working when i am trying to scroll by touching item and why its only working by both sides.
If i miss anything to post please let me know.
You need to remove these lines from Media Fragment Layout. I dont see any purpose for these.
android:isScrollContainer="true"
android:nestedScrollingEnabled="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
I'm trying to dynamically change the text of a textView placed within a BottomAppBar ,but this causes my app to crash. The number of items of the recyclerview which are selected are to be displayed in the textView. This is done in the updateViewCounter(). Everything works fine when the number of selected items are displayed with a Toast.
Here's my code:
public class PhotosFragment extends Fragment {
ArrayList<ImageModel > imageList;
ArrayList<ImageModel> selectedList;
TextView selected_text;
RecyclerView imageRecyclerView;
ImageAdapter imageAdapter;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_photos, container, false);
runtimePermission();
return view;
}
private void runtimePermission() {
Dexter.withContext(getContext()).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
init();
getAllImages();
setImageList();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(), "Permission is Required!", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public void init() {
imageRecyclerView = (RecyclerView) view.findViewById(R.id.photos_recycler);
selected_text = view.findViewById(R.id.selected_textView);
imageList = new ArrayList<>();
selectedList = new ArrayList<>();
}
public void setImageList() {
imageRecyclerView.setLayoutManager((new GridLayoutManager(getContext(), 4)));
imageAdapter = new ImageAdapter(getContext(), imageList);
imageRecyclerView.setAdapter(imageAdapter);
imageAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
#Override
public void onItemViewClick(int position, View v){
try {
if (!imageList.get(position).isSelected) {
selectImage(position);
} else {
unSelectImage(position);
}
} catch (ArrayIndexOutOfBoundsException ed) {
ed.printStackTrace();
}
}
});
};
public void selectImage(int position) {
imageList.get(position).setSelected(true);
imageAdapter.notifyDataSetChanged();
prepareSelection(position);
}
public void prepareSelection(int position) {
if (!selectedList.contains(imageList.get(position))) {
selectedList.add(imageList.get(position));
} else {
selectedList.remove(imageList.get(position));
}
updateViewCounter();
}
public void unSelectImage(int position) {
imageList.get(position).setSelected(false);
imageAdapter.notifyDataSetChanged();
prepareSelection(position);
}
private void updateViewCounter() {
int counter = selectedList.size();
selected_text.setText(valueOf(counter));
}
public void getAllImages(){// queries mediastore }
}
And here's the activity_main.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
tools:ignore="MissingConstraints" >
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimary"
app:tabTextColor="#color/white"
app:tabIndicatorColor="#color/white"
app:tabMode="scrollable"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimaryDark"
android:tintMode="#color/white"
android:src="#android:drawable/arrow_up_float"
app:fabSize="auto"
app:layout_anchor="#id/bottom_app_bar"
app:fabAlignmentMode="end" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottom_app_bar"
style="#style/Widget.MaterialComponents.BottomAppBar.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabCradleMargin="0dp"
app:fabCradleRoundedCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_app_bar_menu">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/selected_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="selected"
android:textColor="#fff"
android:layout_centerInParent="false"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Title"/>
</RelativeLayout>
</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_nav" />
</androidx.drawerlayout.widget.DrawerLayout>
I want to make clicklistener on cardview in my viewpager to startActivity(Intent)
i've tried to make clicklistener with position in setOnPageChangeListener method, but it does not work for me. Please help.
I want to set Intent on cardview.clicklistener, but i don't understand how to set by position, wheter using swith or if method
HERE MY ACTIVITY CODE :
public class Activity extends AppCompatActivity {
ViewPager viewPager;
Adapter adapter;
List<Model> models;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
CardView cardView = findViewById(R.id.cardViewLogin);
//ImageViewPager
models = new ArrayList<>();
models.add(new Model(R.drawable.m,"title", "desc"));
models.add(new Model(R.drawable.d,"title", "desc"));
models.add(new Model(R.drawable.a,"title", "desc"));
adapter = new Adapter(models,this);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
HERE MY ADAPTER CODE :
public class Adapter extends PagerAdapter {
private List<Model> models;
private LayoutInflater layoutInflater;
private Context context;
public Adapter(List<Model> models, Context context) {
this.models = models;
this.context = context;
}
#Override
public int getCount() {
return models.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position)
{
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.item,container,false);
ImageView imageView;
TextView title, desc;
imageView = view.findViewById(R.id.image);
title = view.findViewById(R.id.title);
desc = view.findViewById(R.id.desc);
imageView.setImageResource(models.get(position).getImage());
title.setText(models.get(position).getTitle());
desc.setText(models.get(position).getDesc());
container.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position,
#NonNull Object object) {
container.removeView((View)object);
}
HERE IS MY item.xml CODE :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<androidx.cardview.widget.CardView
android:id="#+id/cardViewLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="20dp"
android:layout_margin="8dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="400dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:src="#drawable/hourglass"
android:layout_height="200dp"
android:scaleType="centerInside"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/image"
android:layout_marginTop="10dp"
android:layout_marginStart="16dp"
android:text="Title"
android:textSize="16sp"/>
<View
android:id="#+id/separator"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/cardview_shadow_start_color"
android:layout_margin="10dp"
android:layout_below="#+id/title"/>
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/separator"
android:layout_marginTop="3dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="20dp"
android:maxLines="3"
android:drawablePadding="10dp"
android:ellipsize="end"
android:text="Description"
android:textSize="16sp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
HERE IS MY XML ACTIVITY LAYOUT CODE :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".UserLoginActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="center"
android:layout_gravity="center"
android:overScrollMode="never"
android:clipToPadding="false">
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
onClick listener of cardView
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos=viewPager.getCurrentItem();
//used switch case
switch (pos) {
case 0:
//Do whatever you want
break;
case 1:
//Do whatever you want
break;
}
});
I have an issue with scrolling Collapsing AppBar, when I am trying to scroll it touching the AppBarLayout part. And also it sometimes scrolling not smoothly.
Here is short (1m 30s) video of issue: https://www.youtube.com/watch?v=n32N9Z4S3SA&feature=youtu.be
Here is link to simple project (only this issue on github): https://github.com/yozhik/Reviews/tree/master/app/src/main/java/com/ylet/sr/review
I'm using: com.android.support:appcompat-v7:27.1.1
There is issue on offsite: https://issuetracker.google.com/issues/37050152
How it is: https://www.youtube.com/watch?v=xWadOVEaTSY&feature=youtu.be
How it should be: https://www.youtube.com/watch?v=J8ITp6RusZo&feature=youtu.be
Does anybody know how to fix this issue you saw on video? I created absolutely simple layouts to avoid any side effects, but bug still reproduced. Thanks in advance.
Description:
CollapsingActivity - activity with Collapsing AppBarLayout. Which loads one or two fragments into "fragment_content_holder" and it has TabLayout
to switch between fragments in view pager.
In activity method onCreate() - I'm just simulating request to server (loadData), and when some fake data is loaded - I am showing fragments in view pager, on first call - I am creating new TabMenuAdapter extends FragmentPagerAdapter, populate it with fragments and save links to instances. On the next call -
I don't create fragments from scratch and just populate them with fresh data.
MenuFragment1, MenuFragment1 - two fragments.
MenuFragment1 - has method public void setupData(SomeCustomData data), to set new data, not recreating fragment on network reconnect.
NetworkStateReceiver - listens to network change and send notifications.
TabMenuAdapter - just simple class to hold fragments.
Next is just copy/paste of code:
public class CollapsingActivity extends AppCompatActivity implements ChangeNetworkNotification {
private static int dataReloadIteration = 0;
private SomeCustomData dummyDataFromServer;
#BindView(R.id.root_layout)
CoordinatorLayout root_layout;
#BindView(R.id.app_bar_layout)
AppBarLayout app_bar_layout;
#BindView(R.id.collapsing_toolbar_layout)
CollapsingToolbarLayout collapsing_toolbar_layout;
#BindView(R.id.view_pager_layout)
ViewPager viewPager;
#BindView(R.id.tab_layout)
TabLayout tabLayout;
#BindView(R.id.collapsing_data_1_txt)
TextView collapsing_data_1_txt;
private NetworkStateReceiver networkStateReceiver;
private boolean isConnected;
protected Fragment currentFragment;
protected Fragment previousFragment;
protected FragmentManager fragmentManager;
private boolean dataLoading = false;
private boolean isCreated = false;
private MenuFragment1 menu1Fragment1;
private MenuFragment2 menu1Fragment2;
private TabMenuAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("TEST", "CollapsingActivity.onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collapsing);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.setNetworkReceiver(this);
IntentFilter intentFilterForNetwork = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkStateReceiver, intentFilterForNetwork);
initToolbar();
loadData();
}
#Override
protected void onStart() {
Log.d("TEST", "CollapsingActivity.onStart");
super.onStart();
IntentFilter intentFilterForNetwork = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkStateReceiver, intentFilterForNetwork);
}
private void initToolbar() {
Log.d("TEST", "CollapsingActivity.initToolbar");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void loadData() {
Log.d("TEST", "CollapsingActivity.loadData");
dataLoading = true;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(CollapsingActivity.this, "Data loaded.", Toast.LENGTH_SHORT).show();
Log.d("TEST", "CollapsingActivity.Data loaded.");
dataReloadIteration++;
dummyDataFromServer = getDummyObjectFromServer();
collapsing_data_1_txt.setText(dummyDataFromServer.Name); //Set data from server in collapsing part of Activity
boolean showOneView = false;
if (showOneView) {
initSingleView();
} else {
if (!isCreated) {
initTabView();
} else {
menu1Fragment1.setupData(dummyDataFromServer); //Set the data from server to fragment, not reloading it, just updating data
}
}
dataLoading = false;
}
});
}
});
t.start();
}
private SomeCustomData getDummyObjectFromServer() {
SomeCustomData dto = new SomeCustomData();
dto.Age = dataReloadIteration;
dto.Name = "Name " + dataReloadIteration;
return dto;
}
private void initSingleView() {
Log.d("TEST", "CollapsingActivity.initSingleView");
tabLayout.setVisibility(View.GONE);
viewPager.setVisibility(View.GONE);
showFragmentWithoutBackStack(R.id.fragment_content_holder, new MenuFragment1());
}
private void initTabView() {
if (!isCreated) {
Log.d("TEST", "CollapsingActivity.initTabView");
tabLayout.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.VISIBLE);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
isCreated = true;
}
}
private void setupViewPager(ViewPager viewPager) {
Log.d("TEST", "CollapsingActivity.setupViewPager");
menu1Fragment1 = MenuFragment1.newInstance(dummyDataFromServer);
menu1Fragment2 = MenuFragment2.newInstance();
adapter = new TabMenuAdapter(getSupportFragmentManager());
adapter.addFragment(menu1Fragment1, "Menu 1");
adapter.addFragment(menu1Fragment2, "Menu 2");
viewPager.setAdapter(adapter);
}
#Override
protected void onDestroy() {
Log.d("TEST", "CollapsingActivity.onDestroy");
super.onDestroy();
unregisterReceiver(networkStateReceiver);
}
#Override
public void networkStateIsChanged(boolean isConnected) {
this.isConnected = isConnected;
Log.d("TEST", "CollapsingActivity.networkStateIsChanged.isConnected: " + isConnected);
if (isConnected) {
Toast.makeText(CollapsingActivity.this, "Connection received.", Toast.LENGTH_SHORT).show();
if (!dataLoading) {
loadData();
}
} else {
Toast.makeText(CollapsingActivity.this, "Connection lost.", Toast.LENGTH_SHORT).show();
}
}
protected void showFragmentWithoutBackStack(int containerViewId, Fragment fragment) {
Log.d("TEST", "CollapsingActivity.showFragmentWithoutBackStack");
previousFragment = currentFragment;
currentFragment = fragment;
String fragmentTag = fragment.getClass().getSimpleName();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (previousFragment != null) {
fragmentTransaction.remove(previousFragment);
}
fragmentTransaction.add(containerViewId, fragment, fragmentTag)
.commitNowAllowingStateLoss();
}
}
activity's layout:
<?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"
android:id="#+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="false"
android:background="#color/white"
android:stateListAnimator="#drawable/appbar_shadow"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/green"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title=""
app:titleEnabled="false">
<include
layout="#layout/appbar_collapsing_part"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize"
app:layout_scrollFlags="scroll|exitUntilCollapsed" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/green"
android:stateListAnimator="#drawable/appbar_shadow"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:theme="#style/ToolbarMenuItemsBackGroundTheme">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title_txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/star_img"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/colorPrimaryDark"
android:textSize="19sp" />
<ImageView
android:id="#+id/star_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_marginEnd="24dp"
android:padding="10dp"
android:src="#drawable/ic_favorite_filled" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#45b0b2"
android:visibility="gone"
app:tabBackground="#drawable/backgr_blue_transparent_selector"
app:tabGravity="center"
app:tabIndicatorColor="#color/colorPrimaryDark"
app:tabIndicatorHeight="2dp"
app:tabMinWidth="500dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextAppearance="#style/CustomTabLayout"
app:tabTextColor="#color/green" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_content_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Fragment 1:
public class MenuFragment1 extends Fragment {
public SomeCustomData transferedDataFromActivity;
private TextView data_1_txt;
public static MenuFragment1 newInstance(SomeCustomData data) {
Log.d("TEST", "MenuFragment1.newInstance");
MenuFragment1 fragment = new MenuFragment1();
Bundle args = new Bundle();
args.putSerializable("DATA_FROM_ACTIVITY", data);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("TEST", "MenuFragment1.onCreate");
if (getArguments() != null) {
this.transferedDataFromActivity = (SomeCustomData) getArguments().getSerializable("DATA_FROM_ACTIVITY");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("TEST", "MenuFragment1.onCreateView");
View v = inflater.inflate(R.layout.menu_fragment_1, container, false);
data_1_txt = (TextView) v.findViewById(R.id.data_1_txt);
setupInOnCreateView();
return v;
}
protected void setupInOnCreateView() {
Log.d("TEST", "MenuFragment1.setupInOnCreateView");
//initialization of all view elements of layout with data is happens here.
setupData(transferedDataFromActivity);
}
public void setupData(SomeCustomData data) {
Log.d("TEST", "MenuFragment1.setupData");
this.transferedDataFromActivity = data;
if (transferedDataFromActivity != null) {
data_1_txt.setText(transferedDataFromActivity.Name);
}
}
}
Fragment 1 layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"
android:orientation="vertical">
<TextView
android:id="#+id/data_1_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/yellow"
android:text="Test"
android:textSize="20sp" />
<include layout="#layout/description_layout" />
</LinearLayout>
Fragment 2:
public class MenuFragment2 extends Fragment {
public static MenuFragment2 newInstance() {
Log.d("TEST", "MenuFragment2.newInstance");
MenuFragment2 fragment = new MenuFragment2();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("TEST", "MenuFragment2.onCreateView");
View v = inflater.inflate(R.layout.menu_fragment_2, container, false);
setupInOnCreateView();
return v;
}
protected void setupInOnCreateView() {
Log.d("TEST", "MenuFragment2.setupInOnCreateView");
//initialization of all view elements of layout with data is happens here.
}
}
Fragment 2 layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/comments_scrollable_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible">
<LinearLayout
android:id="#+id/comments_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/yellow" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/blue" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#color/yellow" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
TabMenuAdapter:
public class TabMenuAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public TabMenuAdapter(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);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Try this
Activity layout
<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">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title=""
app:titleEnabled="false">
<ImageView
android:layout_width="match_parent"
android:layout_height="256dp"
android:scaleType="fitXY"
android:src="#drawable/abc"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_anchor="#id/appBar"
app:tabGravity="fill"
app:tabTextColor="#FFFFFF"
app:tabSelectedTextColor="#ff00"
app:tabMode="scrollable"
app:layout_anchorGravity="bottom" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Activity code
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new BlankFragment(), "TAB-ONE");
adapter.addFragment(new BlankFragment(), "TAB-TWO");
adapter.addFragment(new BlankFragment(), "TAB-THREE");
viewPager.setAdapter(adapter);
}
}
Fragment Code
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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">
<LinearLayout
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".BlankFragment">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="#drawable/kid_goku" />
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="#drawable/kid_goku" />
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_margin="5dp"
android:scaleType="centerCrop"
android:src="#drawable/kid_goku" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
ViewPagerAdapter code
public 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);
}
}
You can see the video here CollapsingToolbarLayout WITH TabLayout
You download the complete project from here CollapsingToolbarLayout WITH TabLayout
Try the below layout foryour activity
<?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/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="false"
android:background="#color/white"
android:stateListAnimator="#drawable/appbar_shadow"
android:theme="#style/AppTheme.AppBarOverlay"
tools:targetApi="lollipop">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/green"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title=""
app:titleEnabled="false">
<include
layout="#layout/appbar_collapsing_part"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize"
app:layout_scrollFlags="scroll|exitUntilCollapsed" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/green"
android:stateListAnimator="#drawable/appbar_shadow"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:theme="#style/ToolbarMenuItemsBackGroundTheme"
tools:targetApi="lollipop">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title_txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/star_img"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:gravity="center_vertical"
android:maxLines="1"
android:textColor="#color/colorPrimaryDark"
android:textSize="19sp" />
<ImageView
android:id="#+id/star_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_marginEnd="24dp"
android:padding="10dp"
android:src="#drawable/ic_favorite_filled" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#45b0b2"
android:visibility="gone"
app:tabBackground="#drawable/backgr_blue_transparent_selector"
app:tabGravity="center"
app:tabIndicatorColor="#color/colorPrimaryDark"
app:tabIndicatorHeight="2dp"
app:tabMinWidth="500dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextAppearance="#style/CustomTabLayout"
app:tabTextColor="#color/green" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_content_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Try scrolling to top in the fragment in the view pager by calling scrollView.fullScroll(View.FOCUS_UP) whenever you click on a tab. If your fragment inside the viewpager is scrolled up then your scrolling should work correctly.
You have done it almost correctly. But need some minor tweaks and modifications.
Step 1 : Set some height to your appBar. Say 224dp.
Step 2 : Set match_parent property to CollapsingToolbarLayout height.
Step 3 : Set following scroll flags to the CollapsingToolbarLayout
`app:layout_scrollFlags = "scroll|enterAlways|enterAlwaysCollapsed"`
Step 4 : Set the toolbar collapsemode to none
Check if it works fine. Let me know.
I have spend a lot of time investigating my issue with AppBar + Collapsing Layouts. And what I did find out is that it's a bug in google support library. So I created the issue for google and they assigned it to one of developers: https://issuetracker.google.com/issues/78686882
But to solve this issue right now I made a workaround - if users will get stuck with scrolling on collapsing part of the layout - they will probably try to click on one of tabs in my TabLayout. So I added code to auto collapse with animation collapsing part of layout: appBarLayout.setExpanded(false, true);
Here is the code:
tabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPagerLayout) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
appBarLayout.setExpanded(false, true);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//no ui effects
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
appBarLayout.setExpanded(false, true);
}
});
To solve this issue, there is a workaround to do on the AppBarLayout :
class CustomAppBarLayout #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppBarLayout(context, attrs, defStyleAttr) {
override fun getBehavior(): CoordinatorLayout.Behavior<AppBarLayout> {
return Behavior().also {
it.setDragCallback(object : Behavior.DragCallback() {
override fun canDrag(appBarLayout: AppBarLayout) = true
})
}
}
}
Found here : https://github.com/material-components/material-components-android/issues/1878
I have a CollapsingToolbarLayout and below that I have a LinearLayout with 2 fragments and a ViewPager. However, when I am scrolling, both fragments stay sticky and only the viewpager containing a RecyclerView is scrolling properly. How can I make both fragments scrollable as well?
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="200dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginBottom="90dp"
app:expandedTitleMarginEnd="64dp">
<ImageView
android:id="#+id/hero"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="top"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/MyCustomTabLayout"
android:layout_gravity="bottom"
app:layout_collapseMode="pin"
app:tabMode="scrollable"/>
<LinearLayout android:id="#+id/ButtonBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center|start"
app:layout_collapseMode="pin"
android:fitsSystemWindows="true"
android:layout_marginTop="40dp"
android:layout_marginLeft="24dp"
android:padding="#dimen/activity_horizontal_margin_half">
<TextView
android:id="#+id/SignUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
android:textAllCaps="true"
android:background="#drawable/rounded_border_white_inverted_selector"
android:textColor="#drawable/rounded_border_white_text_inverted_selector"
android:padding="#dimen/activity_horizontal_margin_half"/>
<TextView
android:id="#+id/LoginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:textAllCaps="true"
android:layout_marginLeft="#dimen/activity_horizontal_margin_half"
android:background="#drawable/rounded_border_white_selector"
android:textColor="#drawable/rounded_border_white_text_selector"
android:padding="#dimen/activity_horizontal_margin_half"/>
</LinearLayout>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/fragmentSponsored"
android:name="SponsoredFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout="#layout/fragment_sponsored" />
<fragment
android:id="#+id/fragmentAnnouncement"
android:name="AnnouncementFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout="#layout/fragment_announcement" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainactivity"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
MyPagerAdapter TabAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
pager.setOffscreenPageLimit(2);
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return SHGCreationFragmentFirst.newInstance("SHGCreationFragmentFirst, Instance 1");
case 1:
return MemberListFragment.newInstance("MemberListFragment, Instance 2");
}
return null;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return 2;
}
}
}
FragmentFirst
public class FragmentFirst extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
return v;
}
public static FragmentFirst newInstance(String text) {
FragmentFirst f = new FragmentFirst();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
FragmentSecond
public class FragmentSecond extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_second, container, false);
return v;
}
public static FragmentSecond newInstance(String text) {
FragmentSecond f = new FragmentSecond();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical"
android:padding="10dp">
</LinearLayout>
fragment_Second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fcfcfc"
android:orientation="vertical"
android:padding="10dp">
</LinearLayout>