Change font of tabs, fontFamily not working - android

I have an issue defining a custom font for tabs in my Xamarin.Forms app (on android).
The Tabbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabTextAppearance="#style/TabbarTitleText"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#android:color/white"
app:tabIndicatorColor="#android:color/white"
app:tabGravity="fill"
app:tabMode="fixed" >
<!--<TextView
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:id="#+id/tabbar_title" />-->
</android.support.design.widget.TabLayout>
I tried to put a textview but doesn't compile.
The style i created in styles.xml is applied except for the fontFamily property
<style name="TabbarTitleText" parent="TextAppearance.AppCompat">
<item name="android:textSize">15dp</item>
<item name="android:fontFamily">fonts/Futura Book.ttf</item>
<item name="android:textAllCaps">false</item>
</style>
Are all parameters correct? Especially parent=
If i use a custom renderer, it doesn't work because there is no child element to detect in TabLayout.
For my Toolbar it works because the TextView receive the custom render parameters.
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:theme="#style/MyActionBar"
android:background="#drawable/custom_background_bar"
android:elevation="3dp">
<TextView
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:id="#+id/toolbar_title" />
.
public class MyToolBarRenderer : NavigationPageRenderer
{
public MyToolBarRenderer(Context context) : base(context)
{
}
private Support.Toolbar _toolbar;
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
if (child.GetType() == typeof(Support.Toolbar))
_toolbar = (Support.Toolbar)child;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var page = this.Element as NavigationPage;
if (page != null && _toolbar != null)
{
Typeface tf = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "fonts/Futura Book.ttf");
TextView title = (TextView)_toolbar.FindViewById(Resource.Id.toolbar_title);
title.SetText(page.CurrentPage.Title, TextView.BufferType.Normal);
title.SetTypeface(tf, TypefaceStyle.Normal);
}
}
}
All my views are NavigationPages, not any TabbedPage.
In App.xaml.cs i have this
MainPage = new NavigationPage(new MainPage())
Then in MainPage
switch (Device.RuntimePlatform)
{
case Device.iOS:
centerPage = new NavigationPage(new Center_Main())
{
Title = TitleCenter
};
......
break;
default:
centerPage = new Center_Main()
{
Title = TitleCenter
};
rightPage = new Right_Main()
{
Title = TitleRight
};
.......
break;
}
Then every xaml is a ContentPage. I basically created a Master Detail project at beginning.

Related

Toolbar does not show up in Xamarin.Android

I'm trying to replace an ActionBar with a toolbar, but the toolbar doesn't show up. I don't understand why my page is still blank without the toolbar, what am I missing?
My style:
<style name="MyThemeActionBar" parent="Theme.AppCompat.Light">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
My toolbar.axml:
<?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:id="#+id/toolbar"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbartitile"
android:text="Kodej"/>
</android.support.v7.widget.Toolbar>
My activity:
[Activity(Label = "MainLoginActivity" , Theme = "#style/MyThemeActionBar")]
public class MainLoginActivity : AppCompatActivity
{
private ISharedPreferences sp;
private Android.Support.V7.Widget.Toolbar toolbar;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MainLogin);
toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
sp = GetSharedPreferences(null, FileCreationMode.Private);
TextView tv = FindViewById<TextView>(Resource.Id.emailMain);
tv.Text = sp.GetString("email", null);
tv.Click += (object sender, EventArgs e) =>
{
Android.Support.V7.App.AlertDialog.Builder ad = new Android.Support.V7.App.AlertDialog.Builder(this);
ad.SetTitle("Logout");
ad.SetMessage("Are you sure you want to logout");
ad.SetPositiveButton("Yes", (senderAlert, args) =>
{
ISharedPreferencesEditor editor = sp.Edit();
editor.Remove("email");
editor.Apply();
StartActivity(typeof(MainActivity));
Finish();
});
ad.SetNegativeButton("Cancel", (senderAlert, args) => {});
Dialog dialog = ad.Create();
dialog.Show();
};
}
}
I think the problem could be with the code:
toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
Since you didn't post your code of your MainLogin layout, when you code this in your MainLoginActivity, the context is MainLoginActivity, and you should make sure there is a Android.Support.V7.Widget.Toolbar which ID is toolbar existing in the MainLogin layout, otherwise, this will return a null, and it won't throw an exception when you SetSupportActionBar(toolbar);.
To solve this issue, you can:
Move your layout for your Toolbar into MainLogin layout.
Or keep your Toolbar in your toolbar layout but use it in your MainLogin layout for example like this:
MainLogin layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include android:id="#+id/toolbar"
layout="#layout/mytoolbar" />
</LinearLayout>

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();
}

How to request focus on TextInputLayout programmatically in case of error?

i have five fields in a form and on validation error message and floating labels are working perfectly but in the case of error when I am calling requestFocus() method on a particular TextInputLayout object then it is not getting focussed.
Code Snippet:
BetterSpinner Spinner_material = (BetterSpinner)rfqItem.findViewById(R.id.Spinner_material);
if(Spinner_material.getText()!=null && Spinner_material.getText().toString().length()>0)
{
TextInputLayout_category.setError(null);
TextInputLayout_category.setErrorEnabled(false);
}
else
{
if(isReporting)
{
TextInputLayout_category.setErrorEnabled(true);
TextInputLayout_category.setError(baseActivity.getString(R.string.addrfq_validationerror_material_category));
TextInputLayout_category.requestFocus();
}
flag=false;
}
XML Snippet :
<android.support.design.widget.TextInputLayout
android:id="#+id/TextInputLayout_category"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.power2sme.android.utilities.customviews.BetterSpinner
android:id="#+id/Spinner_material"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/addrfq_hint_sku_category"
android:imeOptions="actionNext"
android:inputType="textNoSuggestions"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
BetterSpinner is a third party library and it is derived from AutoCompleteTextView.
When requesting focus for a view:
private void requestFocus(View view) {
if (view.requestFocus()) {
yourcoordinatorlayout.clearFocus();
view.requestFocus();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
When clearing all focus in CoordinatorLayout:
private void clearFocusFromAll() {
yourcoordinatorlayout.clearFocus();
}
In you Activity declare CoordinatorLayout like :
CoordinatorLayout yourcoordinatorlayout=(CoordinatorLayout)findViewById(R.id.registerCoordinatorLayout);
And xml will be like :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:id="#+id/registerCoordinatorLayout"
tools:context=".activity.RegisterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme3.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:popupTheme="#style/AppTheme3.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!-- your views will be here, you can add nestedscrollview,layouts etc. -->
<include layout="#layout/content_register" />
</android.support.design.widget.CoordinatorLayout>
i will give one example that are running here in my application.
private boolean validatePassword() {
if (inputPassword.getText().toString().trim().isEmpty()) {
inputLayoutPassword.setErrorEnabled(true);
inputLayoutPassword.setError(getString(R.string.err_msg_password));
requestFocus(inputPassword);
return false;
} else {
inputLayoutPassword.setError(null);
inputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
EDIT
Add my requestFocus method to your code and try below code:
BetterSpinner Spinner_material = (BetterSpinner)rfqItem.findViewById(R.id.Spinner_material);
if(Spinner_material.getText()!=null && Spinner_material.getText().toString().length()>0)
{
TextInputLayout_category.setError(null);
TextInputLayout_category.setErrorEnabled(false);
}
else
{
if(isReporting)
{
TextInputLayout_category.setErrorEnabled(true);
TextInputLayout_category.setError(baseActivity.getString(R.string.addrfq_validationerror_material_category));
requestFocus(Spinner_material);
}
flag=false;
}

Visible ActionBar with opened NavDrawer

Is it possible to keep the actionbar visible using the mikepenz's material drawer library?
Yes this is possible. Just see the sample application. This contains the CustomContainerActivity which showcases how you can have a Drawer which is below the Toolbar
public class CustomContainerActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_custom_container_dark_toolbar);
// Handle Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.drawer_item_custom_container_drawer);
//Create the drawer
result = new DrawerBuilder(this)
//this layout have to contain child layouts
.withRootView(R.id.drawer_container)
.withToolbar(toolbar)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_home),
new PrimaryDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_gamepad),
new PrimaryDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_eye),
new SectionDrawerItem().withName(R.string.drawer_item_section_header),
new SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog),
new SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_question).withEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesome.Icon.faw_github),
new SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_bullhorn)
)
.withSavedInstance(savedInstanceState)
.build();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
}
Also note the different xml layout which is used in this Activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp" />
<!-- the layout which will contain (host) the drawerLayout -->
<FrameLayout
android:layout_below="#id/toolbar"
android:id="#+id/drawer_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the layout which will be the content of the activity (which will be hosted inside the drawer (NOT the list of the drawer)) -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtLabel"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:textSize="16sp" />
</FrameLayout>
</FrameLayout>
</RelativeLayout>
This will produce the following:

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

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.

Categories

Resources