Hiding/Showing the toolbar when fragment in the tabs is scrolled - android

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.

Related

Load webview in the top of the page

I'm working in a WebView App.
In my last change, i added a function to hide the app bar when i scroll down in webview. Nice !!!
But i have noticed a problem. I will try explain.
Let's suposse that i'm in a News Site, and i'm openning the last news. The most recent news are in the start of the page, and the last news are close to the ends of the page, so i open the last news, and my webview load the url. When the url is loaded, my webview is in the end of the site, and not in the start. It started after i added my "webview" inside of "NestedScrollView". Looks like NestedScrollView is saving my position, and it's affecting my position in the web page. How to fix this ?
Edit: My webview is load inside Framelayout, my webview is a fragment.
WebView Layout
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipelayout">
<android.support.v4.widget.NestedScrollView 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:layout_gravity="fill_vertical"
>
<WebView
android:id="#+id/inicio_pagina"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"></WebView>
</android.support.v4.widget.NestedScrollView>
FrameLayout
<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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
App_Bar_Main
<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.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main"
android:id="#+id/include" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/face"
android:scaleType="center"/>
Edit 2: WebView Fragment
public class InicioPagina extends Fragment {
private ProgressBar prg;
SwipeRefreshLayout mySwipeRefreshLayout;
NestedScrollView NestedScrollView;
public WebView myWebView;
public static InicioPagina newInstance() {
InicioPagina fragment = new InicioPagina();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.iniciopagina, container, false);
prg = (ProgressBar)rootView.findViewById(R.id.progressBar2);
NestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nested_scroll_view);
mySwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipelayout);
myWebView = (WebView) rootView.findViewById(R.id.inicio_pagina);
myWebView.loadUrl("http://google.com.br/");
//*Ativar JavaScript
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//*Forçar links para abrir no WebView ao invés do navegador
myWebView.setWebViewClient(new WebViewClient());
NestedScrollView.scrollTo(0, 0);
myWebView.setVerticalScrollBarEnabled(false);
mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
myWebView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
});
myWebView.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
public class WebViewClient extends android.webkit.WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
prg.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
prg.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
1) Make id for the NestedScrollView
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_vertical">
2) Create NestedScrollView object
3) When the new URL is loaded, set the scroll property of the nestedScrollViewobject to 0,0.
nestedScrollViewObj.scrollTo(0, 0);

Some questions on Android UI

Please, anybody help me. I have a 2 big problem:
App bar moves my left button to center app, right after string:
setSupportActionBar(mToolbar)
buttons - wrap/wrap, tryed to wrap her in RelativeLayout, tryed to set "anchor" parameter - no effect - title moves her then appears.
Fragments appears higher then fragmentContainer - on my appbar.
My idea was - 1 main activity + 3 fragments changes in her bottom part, and settings-activity. Screen applied.
Also I have a question:
For now I changes fragment using .replace - method. If I do it then I send search query and receive list of elements - it would create a new main fragment with empty list? But now it's not important. Of course, I can get fragments by tag, if one exists.
Code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
style="#style/match">
<android.support.design.widget.AppBarLayout
style="#style/fill"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="72dp"
android:background="#color/colorPrimary"
app:theme="#style/ToolBarStyle"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:layout_collapseMode="pin">
<RelativeLayout
style="#style/wrap">
<ImageView
android:id="#+id/settings_btn"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_alignParentLeft="true"
android:src="#drawable/servis"
android:contentDescription="#string/settings.title"
android:fitsSystemWindows="true"/>
</RelativeLayout>
<ImageView
android:id="#+id/logout_btn"
android:layout_width="24dp"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="#dimen/spacing_normal_16"
android:layout_weight="0.5"
android:src="#drawable/off"
android:contentDescription="#string/main.logout"
android:cropToPadding="false"/>
</android.support.v7.widget.Toolbar>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/black"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
style="#style/fill"
app:layout_scrollFlags="scroll|snap">
<android.support.design.widget.TabItem
android:id="#+id/search_tab"
style="#style/wrap"
android:text="#string/main.search"/>
<android.support.design.widget.TabItem
android:id="#+id/saved_tab"
style="#style/wrap"
android:text="#string/main.saved"/>
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content"/>
</android.support.design.widget.CoordinatorLayout>
content.xml (like in books):
<?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:id="#+id/fragmentContainer"
style="#style/match"
tools:context=".ui.activities.MainActivity"/>
fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/match">
<android.support.v7.widget.RecyclerView
android:id="#+id/audio_list"
style="#style/recycler_view"/>
... <buttonsLayout>
</RelativeLayout>
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DataManager mDataManager;
private Toolbar mToolbar;
private ImageView mSettings, mLogout;
private TabLayout mTabLayout;
private TabItem mSearchTab, mSavedTab;
private int accentColorId, primaryColorId;
private String mQuery;
public void setQuery(String query) {
mQuery = query;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataManager = DataManager.getInstance();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//mToolbar.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
mSettings = (ImageView) findViewById(R.id.settings_btn);
mSettings.setOnClickListener(this);
mLogout = (ImageView) findViewById(R.id.logout_btn);
mLogout.setOnClickListener(this);
accentColorId = getResources().getColor(R.color.colorAccent);
primaryColorId = getResources().getColor(R.color.colorPrimary);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mSearchTab = (TabItem) findViewById(R.id.search_tab);
mSavedTab = (TabItem) findViewById(R.id.saved_tab);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
//mSearchTab.setBackgroundColor(accentColorId);
//mSavedTab.setBackgroundColor(primaryColorId);
showFragment(SearchFragment.newInstance(mQuery), "search");
} else if(tab.getPosition() == 1) {
showFragment(new SavedFragment(), "saved");
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {}
#Override
public void onTabReselected(TabLayout.Tab tab) {}
});
mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
signIn();
}
...
private void showFragment(Fragment fragment, String tag) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.replace(R.id.fragmentContainer, fragment, tag)
.addToBackStack(tag)
.commit();
}

Android Flowing Drawer

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.

How can I set tabs at the bottom and also hide top actionbar?

In my application I am using actionbar tabs at bottom. I have searched many tutorials but I am not understanding the solutions. Most of the answers said to use TabActivity, but that is deprecated. So can any one tell me how can approach this?
The best way to implement tabs now is to use a TabLayout from the design library.
Here is an example of a TabLayout aligned at the bottom of the screen.
First set up the dependencies in the build.gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}
Here is the layout xml for the Main Activity:
<RelativeLayout
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.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
Here is the Activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three", };
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BlankFragment();
case 1:
return new BlankFragment();
case 2:
return new MapFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/custom_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:textSize="16dip"
android:textColor="#ffffff"
android:singleLine="true"
/>
</LinearLayout>
App theme in styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- your app branding color for the app bar -->
<item name="colorPrimary">#3F51B5</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="colorPrimaryDark">#303F9F</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="colorAccent">#FF4081</item>
</style>
Result:
If you want to hide the ActionBar, just remove the toolbar from the layout xml, and remove the toolbar code from the Activity, and make sure to use Theme.AppCompat.Light.NoActionBar in the AppTheme. The result of those changes would make it look like this:
this is an example
Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar_bottom);
toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.action_settings:
// TODO
break;
// TODO: Other cases
}
return true;
}
});
// Inflate a menu to be displayed in the toolbar
toolbarBottom.inflateMenu(R.menu.menu_main);
and this xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_bottom"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
android:layout_alignParentBottom="true"
android:minHeight="?attr/actionBarSize" />
Step 1 - Create a custom layout for your toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
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="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
Step 2 - Include this layout into your activity layout. Give it the bottom position.
<include
android:id="#+id/toolbar_main"
layout="#layout/main_toolbar" />
Step 3 - Call the toolbar into your activity and done. It will behave as any toolbar but positioned at bottom.

Hide toolbar on scroll when the using a recyclerview inside a Fragment instead of an Activity

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.

Categories

Resources