I'm using ViewPager inside fragment. The viewpager contains two fragments.
My problem when I go back to this fragment i got a blank fragment (it works only in the first time).
ViewPager Code :
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new ListeMagasinsFragment(), getActivity().getString(R.string.liste));
adapter.addFragment(new MapMagasinsFragment(), getActivity().getString(R.string.carte));
viewPager.setAdapter(adapter);
}
I also overrided onBackPressed() :
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
//super.onBackPressed();
}
}
This code below shows the fragment transaction :
Fragment fragment = new MagasinDetailsFragment();
if (fragment != null) {
Bundle bundles = new Bundle();
if (magasin != null) {
bundles.putSerializable("magasin", (Serializable) magasin);
Log.e("magasin", "is valid");
} else {
Log.e("magasin", "is null");
}
fragment.setArguments(bundles);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
More code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_magasins, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager)view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
Fragment xml :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabGravity="fill"/>
</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" />
main_activity.xml :
<android.support.v4.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"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
/>
And content_main.xml :
<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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.carrefour.creova.carrefourmobile.activities.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Any ideas ?
In your Activity override the onBackPressed() method.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else{
finish();
}
}
You must have added the fragments to the BackStack for this to work, something similar to:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("variable_if_needed", "Some Value");
getFragmentManager().beginTransaction()
.replace(R.id.relativecontent, fragment)
.addToBackStack(null)
.commit();
return true;
"R.id.relativecontent" should be your Fragment container.
Is it actually necessary to go back to the previous page in the viewPager when you press the back button? That is not something I have seen often. For one, the previous page(Fragment) should be a left or right swipe away from the current one, and you may implement an AlertDialog to prompt the user to see if he wants to exit the app instead.
I have gone through these but does not seems to work
working with
android.support.design.widget.TabLayout
needs to set custom views to each child tab as a match parent to child size
pragmatically give a size
View v = LayoutInflater.from(this).inflate(R.layout.layout_two, null);
v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
tabLayout.getTabAt(0).setCustomView(v);
this works as a match parent because there is no background but once add a inflate view issue comes
tabLayout.getTabAt(1).setText("About").setIcon(R.drawable.drop_complete);
though about the tabIndicator as well
setting its height to app:tabIndicatorHeight="0dp" or adding android:tabStripEnabled="false" does not help.
here is a picture with boundaries which clearly shows the small gap like padding(blue bar is my TabLayout with two tabs )
left one is inflated
right one is normal .setIcon
any help to make inflated one match parent with no gaps ?
Here is my code
XML
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="30dp">
//------- INSIDE THIS I HAVE A TAB
<android.support.v7.widget.Toolbar
android:background="#drawable/capture"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:elevation="0dp"
app:layout_scrollFlags="scroll|enterAlways"
/>
//------ HERE comes THE TAB That I DEAL
<android.support.design.widget.TabLayout
android:tabStripEnabled="false"
app:tabIndicatorHeight="0dp"
android:id="#+id/tab_layout"
android:scrollbars="none"
android:layout_below="#+id/toolbar"
android:layout_width="fill_parent"
android:layout_height="match_parent"
app:tabTextColor="#d3d3d3"
android:minHeight="?attr/actionBarSize"
android:orientation="vertical" >
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:background="#467"
android:id="#+id/viewpager"
android:layout_below="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
myClass
public class LayoutExampleActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_example);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPagerAdaptor(viewPager);
tabLayout.setupWithViewPager(viewPager);
setTabs();
}
private void setupViewPagerAdaptor(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "First");
adapter.addFragment(new GalleryFragment(), "Second");
// adapter.addFragment(new FragmentOne(), "Third");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void setTabs() {
tabLayout.getTabAt(0).setCustomView(R.layout.layout_one);
tabLayout.getTabAt(1).setText("About").setIcon(R.drawable.drop_complete);
}
}
Set tabPaddingStart and tabPaddingEnd attributes.
like this:
<android.support.design.widget.TabLayout
...
app:tabPaddingStart="0dp"
app:tabPaddingEnd="0dp" >
This question might be duplicated.
see: Cannot remove Padding from Tabs when using Custom views with Tab Layout
I'm following this link and using this exact same code to make this flowing drawer but i'm using eclipse and for the life of me i can't figure out the problem.
Iam using exact this code so i don't know what to post here.
I'll just post my main activity here. In logcat its crashing on setcontentview. I'll also post my .xml file
public class MainActivity extends AppCompatActivity {
private RecyclerView rvFeed;
private LeftDrawerLayout mLeftDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Calling Layout");
setContentView(R.layout.activity_main);
System.out.println("Layout Called");
setupToolbar();
mLeftDrawerLayout = (LeftDrawerLayout) findViewById(R.id.id_drawerlayout);
rvFeed = (RecyclerView) findViewById(R.id.rvFeed);
FragmentManager fm = getSupportFragmentManager();
MyMenuFragment mMenuFragment = (MyMenuFragment) fm.findFragmentById(R.id.id_container_menu);
FlowingView mFlowingView = (FlowingView) findViewById(R.id.sv);
if (mMenuFragment == null) {
fm.beginTransaction().add(R.id.id_container_menu, mMenuFragment = new MyMenuFragment()).commit();
}
mLeftDrawerLayout.setFluidView(mFlowingView);
mLeftDrawerLayout.setMenuFragment(mMenuFragment);
setupFeed();
}
protected void setupToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_menu_white);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mLeftDrawerLayout.toggle();
}
});
}
private void setupFeed() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
#Override
protected int getExtraLayoutSpace(RecyclerView.State state) {
return 300;
}
};
rvFeed.setLayoutManager(linearLayoutManager);
FeedAdapter feedAdapter = new FeedAdapter(this);
rvFeed.setAdapter(feedAdapter);
feedAdapter.updateItems();
}
#Override
public void onBackPressed() {
if (mLeftDrawerLayout.isShownMenu()) {
mLeftDrawerLayout.closeDrawer();
} else {
super.onBackPressed();
}
}
}
<com.abc.epicfloatinglibrary.LeftDrawerLayout
android:id="#+id/id_drawerlayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
>
<!--content-->
<android.support.v7.design.widget.CoordinatorLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvFeed"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/toolbar"
layout="#layout/view_feed_toolbar" />
</android.support.design.widget.AppBarLayout>
<!--menu-->
<RelativeLayout
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:clipChildren="false"
>
<com.abc.epicfloatinglibrary.FlowingView
android:id="#+id/sv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/id_container_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_marginRight="25dp"
android:paddingRight="10dp"
/>
</RelativeLayout>
Try the following.
Clean your project,
Rebuild your project,
Get Build on Gradle.
If you'll not get it run, check your build.gradle file whether you have added that library in dependencies.
I added the new Toolbar, Tablayout and Viewpager in my android app. I provided Fragments for my 3 Tabs and its working fine. But the problem is that when i scroll up my Toolbar does not hide. I want that when i scroll my fragment it should hide. And one more thing, i am using Webview in the fragment.
My codes are given below.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupToolbar();
setupTablayout();
}
private void setupToolbar() {
// TODO Auto-generated method stub
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarsdfs);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);}
}
private void setupTablayout() {
// TODO Auto-generated method stub
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
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) {
}
});
}
}
main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarsdfs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:layout_scrollFlags="scroll|enterAlways"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:scrollbars="horizontal"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/tablayout"/>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
PagerAdapter.Java
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment_Feeds tab1 = new Fragment_Feeds();
return tab1;
case 1:
Fragment_Facts tab2 = new Fragment_Facts();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Fragment_Feeds.java
public class Fragment_Feeds extends Fragment {
SwipeRefreshLayout swipeView;
WebView myWebView;
ProgressBar progressBar;
final static String myBlogAddr = "http://myblog.com";
String myUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentfeeds, container, false);
swipeView = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
myWebView = (WebView) view.findViewById(R.id.webview);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setHorizontalScrollBarEnabled(false);
myWebView.loadUrl("http://myblog.com");
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
#Override
public void onRefresh()
{
myWebView.loadUrl("http://myblog.com");
}});
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
swipeView.setRefreshing(false);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myUrl = url;
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
myWebView.loadUrl("file:///android_asset/error_page.html");
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
fragmentfeeds.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FFFFFF" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">s
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="1"
android:scrollbars="none"
android:focusableInTouchMode="false"
android:focusable="false"
android:background="#FFFFFF" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
What i want?
What i want is that when i scroll the webview upwards, the toolbar should also scroll upwards and hides and when i scroll back down the toolbar should come back as soon as possible.
Try this.
main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_height="match_parent"
android:layout_width="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.support.v7.widget.Toolbar
android:id="#+id/toolbarsdfs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:scrollbars="horizontal"
android:layout_below="#+id/toolbarsdfs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#android:color/white"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="3dp" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_below="#+id/tablayout"/>
</android.support.design.widget.CoordinatorLayout>
fragmentfeeds.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:isScrollContainer="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical"
android:clipToPadding="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<WebView
android:id="#+id/webviewtool"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="1"
android:focusableInTouchMode="false"
android:focusable="false"
android:background="#FFFFFF" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Firstly, You should move your webview into NestedScrollView and set 'android:isScrollContainer' property to 'false' value. https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html
Secondly, You should move your ViewPager outside the AppBarLayout.
So, your main.xml should be like this:
<?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/main_content"
android:background="#FFF"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<!-- your app bar stuff here -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="240dp"
app:layout_scrollFlags="scroll|enterAlways">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:id="#+id/image_header"/>
<include layout="#layout/header"/>
</FrameLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:background="#FFF"
app:tabTextColor="#a3a3a3"
app:tabSelectedTextColor="#a3a3a3"
app:tabIndicatorColor="#0042ab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#eaeaea"/>
AppBarLayout childern will hide only if they have flag app:layout_scrollFlags
Read more about implementing support design library here:
https://android-developers.googleblog.com/2015/05/android-design-support-library.html
You should move your ViewPager outside the AppBarLayout and add behavior to ViewPager app:layout_behavior="#string/appbar_scrolling_view_behavior"
I wrote a full example!
https://github.com/erikcaffrey/AndroidDesignSupportLibrary
I hope it help you!
Have a look at
How to properly hide&show the actionbar using the new design library API?
Android-ObservableScrollView
im sorry about my english.
I'll show you how i've made that for my app (min sdk: 14, target sdk: 22). I dont use fragments, i only have a single webview in my activity, but the handler is the same. The probles is when you make scroll inside a webview, Android doesn't handle that like a scroll event, the webview handles his own events.
First i define the styles.xml in res folder. I use a transparent and overlayed ActionBar, thats better when you want to hide and show that:
res/styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="#android:style/Theme.Holo">
<!-- Customize your theme here. -->
<item name="android:windowActionBarOverlay">true</item>
<item name="android:actionBarStyle">#style/MyActionBar</item>
</style>
<!-- ACTION BAR STYLES -->
<style name="MyActionBar" parent="#android:style/Widget.Holo.ActionBar">
<item name="android:background">#color/actionbar_background</item>
</style>
</resources>
then at the manifest, i define the styles for the app and the ActionBar in the application section:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
finally in the MainActivity, you must control the gestures in the webview. You must implements the View.OnTouchListener, and the Handler.Callback. When you touch on the webview, you must compare the start event and the end event:
MainActivity.Java
public class MainActivity extends Activity implements View.OnTouchListener, Handler.Callback {
private float x1,x2,y1,y2; //x1, y1 is the start of the event, x2, y2 is the end.
static final int MIN_DISTANCE = 150; //min distance for a scroll up event
private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;
private static final int UP_ON_WEBVIEW = 3;
private final Handler handler = new Handler(this);
public WebView webView;
private WebViewClient client;
private WebAppInterface webAppInt = new WebAppInterface(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.myWebView);
webView.setOnTouchListener(this);
client = new WebViewClient();
webView.setWebViewClient(client);
webView.loadDataWithBaseURL("file:///android_asset/", "myweb.html", "text/html", "UTF-8", "");
}
//HERE START THE IMPORTANT PART
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.myWebView && event.getAction() == MotionEvent.ACTION_DOWN){
x1 = event.getX();
y1 = event.getY();
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 200);
} else if (v.getId() == R.id.myWebView && event.getAction() == MotionEvent.ACTION_UP){
x2 = event.getX();
y2 = event.getY();
handler.sendEmptyMessageDelayed(UP_ON_WEBVIEW, 200);
}
return false;
}
#Override
public boolean handleMessage(Message msg) {
if (msg.what == CLICK_ON_URL){ //if you clic a link in the webview, thats not a scroll
handler.removeMessages(CLICK_ON_WEBVIEW);
handler.removeMessages(UP_ON_WEBVIEW);
return true;
}
if (msg.what == CLICK_ON_WEBVIEW){
Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
return true;
}
if (msg.what == UP_ON_WEBVIEW){
float deltaX = x2 - x1; //horizontal move distance
float deltaY = y2 - y1; //vertical move distance
if ((Math.abs(deltaX) > MIN_DISTANCE) && (Math.abs(deltaX) > Math.abs(deltaY)))
{
// Left to Right swipe action
if (x2 > x1)
{
Toast.makeText(this, "Left to Right swipe [Next]", Toast.LENGTH_SHORT).show ();
}
// Right to left swipe action
else
{
Toast.makeText(this, "Right to Left swipe [Previous]", Toast.LENGTH_SHORT).show ();
}
}
else if ((Math.abs(deltaY) > MIN_DISTANCE) && (Math.abs(deltaY) > Math.abs(deltaX)))
{
// Top to Bottom swipe action -- i SWOW MY ACTIONBAR ON SCROLLDOWN
if (y2 > y1)
{
getActionBar().show();
Toast.makeText(this, "Top to Bottom swipe [Show Bar]", Toast.LENGTH_SHORT).show ();
}
// Bottom to top swipe action -- I HIDE MY ACTIONBAR ON SCROLLUP
else
{
getActionBar().hide();
Toast.makeText(this, "Bottom to Top swipe [Hide Bar]", Toast.LENGTH_SHORT).show ();
}
}
return true;
}
return false;
}
}
I hope thats helps you.
To hide the menu for a specific fragment:
setHasOptionsMenu(true); //Inside of onCreate in FRAGMENT:
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search).setVisible(false);
}
Just add this line in your toolbar or FAB button.
app:layout_scrollFlags="scroll|enterAlways"
The app:layout_scrollFlags="scroll|enterAlways" line will cause that our Toolbar will scroll of the screen when user scrolls down the list and as soon as he starts scrolling up the Toolbar will show up again. Clean and simple, that’s the power of CoordinatorLayout!
Kindly have look over this link
https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling(part3)/&re=1&ts=1453224208&sig=ALL1Aj5aKrtAlylt-Qt3Ci6uwff76BqQYw
Simply putting app:layout_scrollFlags="scroll|enterAlways" onto your toolbar will suffice.
I'm trying to adapt the strategy for hiding / showing a toolbar (or any visual element) from the well explained and great article:
http://mzgreen.github.io/2015/02/15/How-to-hideshow-Toolbar-when-list-is-scroling%28part1%29/
But in my case I'm using a Fragment to hold the recycleview instead of the activity. My problem is that the padding is not being applied so the first element is under the toolbar, and I have also another strange behavior, as the toolbar is also under the statusbar. I don't know what is happening here.
The following are my "moving pieces":
BasicActivity.java: based on the one given on the previous post, but moving away the recycleview part as is going to be on the Fragment piece. Also it exposes the show and hide methods to allow the fragment to access it:
public class BasicActivity extends ActionBarActivity {
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container,new RecycleFragment())
.commit();
overridePendingTransition(0, 0);
initToolbar();
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
setTitle(getString(R.string.app_name));
mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
}
public void hideViews() {
mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
}
public void showViews() {
mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
}
}
My activiy_basic.xml is the following:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<include layout="#layout/toolbar_actionbar" />
</FrameLayout>
The layout toolbar_actionbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:clipToPadding="false"/>
The Fragment RecycleFragment.java:
public class RecycleFragment extends Fragment {
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initRecyclerView(view);
}
private void initRecyclerView(View view) {
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setOnScrollListener(new HidingScrollListener() {
#Override
public void onHide() {
((BasicActivity)getActivity()).hideViews();
}
#Override
public void onShow() {
((BasicActivity)getActivity()).showViews();
}
});
}
private List<String> createItemList() {
List<String> itemList = new ArrayList<>();
for(int i=0;i<20;i++) {
itemList.add("Item "+i);
}
return itemList;
}
}
And the layout for the fragment is just a recyclerview fragment_recycler.xml:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
The adapter and the viewholder for the recycler are the same as the article, and they doesn't affect the behavior.
What is wrong with the code?
UPDATE:
A Michał Z. below pointed out. What was missing is the paddingTop and clipptoPadding on the Recyclerview view
So the final xml should be:
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize"
android:clipToPadding="false"/>
And to solve the statusbar overlapping problem, it is needed to add a "fitsystemwindows" = "true" element on the activity layout. So it must be as the following:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<FrameLayout android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<include layout="#layout/toolbar_actionbar" />
</FrameLayout>
UPDATE2
The fitSystemWindows is only needed if the theme is setting the statusbar as translucent
Your fragment_recycler.xml file is missing paddingTop and clipToPadding attributes.
It should look like this:
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize"
android:clipToPadding="false"/>
And also remove clipToPadding from your toolbar_actionbar.xml.