How to hide and show FloatingActionButton with Fragments in a ViewPager? - java

I am trying to only show my FloatingActionButton on one fragment and hide in the rest. I have tried multiple answers and nothing is working. I tried this solution:
Hide a Floating Action Button of another Layout
But it isn't working. I tried adding buttons on two of the fragments, one that shows and one that hides the FAB and that works, but once I remove the button, it won't show automatically. Here is my code:
hidden_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
shown_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
HiddenFragment.java:
public class HiddenFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.hidden_fragment, container, false);
final FloatingActionButton fab = ((MainActivity) getActivity()).getFloatingActionButton();
if (fab != null) {
((MainActivity) getActivity()).hideFloatingActionButton();
}
return view;
}
}
ShownFragment.java:
public class ShownFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.hidden_fragment, container, false);
final FloatingActionButton fab = ((MainActivity) getActivity()).getFloatingActionButton();
if (fab != null) {
((MainActivity) getActivity()).showFloatingActionButton();
}
return view;
}
}
In my MainActivity.java I have this:
public FloatingActionButton getFloatingActionButton() {
return fab;
}
public void showFloatingActionButton() {
fab.show();
}
public void hideFloatingActionButton() {
fab.hide();
}
The way I currently have it doesn't work. When I launch the app, the first fragment launched is the HiddenFragment. But when I go to the ShownFragment, the FAB doesn't appear. I tried a different approach, I added a button to each fragment and added the showFloatingActionButton() and hideFloatingActionButton() to the buttons and that works. Does anyone know what I am doing wrong?

For showing/hiding a FloatingActionButton with Fragments in a ViewPager, just use a ViewPager.OnPageChangeListener and show the FloatingActionButton for the positions you want, and hide it for the positions you want.
This would go in the Activity:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.hide();
break;
case 1:
fab.show();
break;
case 3:
fab.hide();
break;
default:
fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Hide the floating button from other fragment. It work in my case.
in MainActivity.java add:
private ActivityMainBinding binding;
public FloatingActionButton getFloatingActionButton() {
return binding.fab;
}
onCreateView in SecondFragment:
private FloatingActionButton floatingButton;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
floatingButton = ((MainActivity) getActivity()).getFloatingActionButton();
floatingButton.hide();
...
}

Related

swipe tablayout is not working correctly

i am using "compile 'com.android.support:design:25.1.0'" to implement swipe tablayout. My code has no syntax error but due to some logical error it is not working correctly
Problems: 1) when i slide a page it should move on next tab but it slide or move very slowly and go between two tabs
2) when i come back on privious tabs sometime it does not show even any page and sometime it show wrong page e.g on second tabs it shows third page(fragment)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout;
String[] tabs={"SCORES","NEWS","SERIES"};
tabLayout=(TabLayout) findViewById(R.id.cricTabLayout);
tabLayout.addTab(tabLayout.newTab().setText(tabs[0]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[1]));
tabLayout.addTab(tabLayout.newTab().setText(tabs[2]));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(Color.parseColor("#627179"), Color.parseColor("#BF4A32"));
final ViewPager viewPager=(ViewPager)findViewById(R.id.cricPagerView);
final PageAdapter pageAdapter=new PageAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
// new line
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// viewPager.clearOnPageChangeListeners();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// Toast.makeText(MainActivity.this,"Tab changed",Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PageAdapter.java
public class PageAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new ScoreFragment();
case 1:
return new NewsFragment();
case 2:
return new SeriesFragment();
default: return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
ScoreFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
SeriesFragment.java
public class ScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"Score",Toast.LENGTH_LONG).show();
return view;
}
}
NewsFragment.java
public class NewsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=null;
Toast.makeText(getContext(),"News",Toast.LENGTH_LONG).show();
return view;
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/activity_news"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.apple.crickapp.MainActivity"
android:layout_marginLeft="0dp">
<android.support.design.widget.TabLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:elevation="8dp"
android:background="#color/colorBlack"
android:minHeight="?attr/actionBarSize"
android:id="#+id/cricTabLayout"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/cricPagerView"
android:layout_below="#id/cricTabLayout"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>

Can't drag or zoom google map inside a Listview android

I have added a map Fragment to a ListView. It works fine but it can't drag or zoom.
MainActivity.java
mapviewheader = getActivity().getLayoutInflater().inflate(R.layout.view_header, mListView, false);
FrameLayout map_container = (FrameLayout) mapviewheader.findViewById(R.id.map_container);
FragmentTransaction mTransaction = this.getChildFragmentManager().beginTransaction();
mapFragment = new SupportMapFragment().newInstance();
//mapFragment.setOnTouchListener
mTransaction.add(map_container.getId(), mapFragment);
mTransaction.commit();
try {
MapsInitializer.initialize(getActivity());
} catch (Exception e) {
e.printStackTrace();
}
mListView.setParallaxView(mapviewheader);
view_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/map_container"
android:layout_width="match_parent"
android:layout_height="400dp"
/>
</LinearLayout>
I have tried to use onTouchListener(...) but it doesn't work for me.
That's because the ListView is already catching the touch events. You'll have to let your map Fragment catch them. For this you could extends the MapSupportFragment you are using.
public class TouchableGoogleMapFragment extends SupportMapFragment {
private OnTouchListener mListener;
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);
TouchableWrapper frameLayout = new TouchableWrapper(getActivity());
// make it invisible
frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
((ViewGroup) layout).addView(frameLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return layout;
}
public void setListener(OnTouchListener listener) {
mListener = listener;
}
public interface OnTouchListener {
public abstract void onTouch();
}
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mListener.onTouch();
break;
case MotionEvent.ACTION_UP:
mListener.onTouch();
break;
}
return super.dispatchTouchEvent(event);
}
}
}
And then, in your MainActivity you'll have to requestDisallowInterceptTouchEvent(true) when the user touch the Fragment:
// Intercepting touch events
mapFragment.setListener(new TouchableGoogleMapFragment.OnTouchListener() {
#Override
public void onTouch() {
mScrollView.requestDisallowInterceptTouchEvent(true);
}
});

What's wrong with my dynamically placed Fragment?

I want to rewrite my activities to dialogs, and I want to replace dialogs programmatically. I tried fragments staticaly and it is works fine. When I programmatically call fragment and debug it with breakpoints I don't understand why its lifecycle starts from onCreate() and ends on it... Why from onCreate() and don't from onAttach() like when I call it statically? here is my code, help me plz!!!
base_activity.xml `
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/base_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/base_fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
`
BaseActivity.java
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_activity);
DietsFragment dietsFragment = new DietsFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.base_fragment_holder, dietsFragment);
fragmentTransaction.commit();
}
}
DietsFragment.java
public class DietsFragment extends Fragment
implements AdapterView.OnItemClickListener,
View.OnClickListener {
public FragmentEventListener fragmentEventListener;
Cursor diets;
DietAdapter adapter;
DietHelper helper;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.activity_diets, container, false);
listView = (ListView) view.findViewById(R.id.act_diets_lv_diets);
if (listView != null) {
listView.setOnItemClickListener(this);
}
FloatingActionButton floatingActionButton = (FloatingActionButton) view.findViewById(R.id.act_diets_fab);
if (floatingActionButton != null)
floatingActionButton.setOnClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setHelper(new DietHelper(getActivity()));
setDiets(getHelper().getAllTableRecordsCursor());
setAdapter(new DietAdapter(getActivity(), getDiets()));
listView.setAdapter(getAdapter());
fragmentEventListener = (FragmentEventListener) getActivity();
}
public void setDiets (Cursor diets) {
this.diets = diets;
}
public void setAdapter (DietAdapter adapter) {
this.adapter = adapter;
}
public void setHelper (DietHelper helper) {
this.helper = helper;
}
public Cursor getDiets() {
return diets;
}
public DietAdapter getAdapter() {
return adapter;
}
public DietHelper getHelper() {
return helper;
}
}
in DietsFragment and BaseActivity i hide its implementetions of OnClickListener, OnItemClickListener and FragmentEventListener, cause it works fine when i add fragment in BaseActivity statically from xml with
I've just found my mistake... I overloaded findViewbyId(int resId) in BaseActivity and that all my problem, and now i'm asking myself WHY I OVERLOAD THAT METHOD WHAT WAS I WANTED TO DO WITH IT?

Android : Acess pagerAdapter layout listview with ViewPager and AsyncTask

I have a pagerAdapter like this :
public class AppPagerAdapter extends PagerAdapter {
Context context;
public AppPagerAdapter(Context appcon)
{
this.context = context;
}
#Override
public int getCount() {
return 10;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View viewItem = inflater.inflate(R.layout.pager_layout, container, false);
ListView listView = (ListView) viewItem.findViewById(R.id.list);
}
}
And in my XML is this : "pager_layout.xml"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:wheel="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:id="#+id/list"
android:divider="#color/activity_background"
android:layout_height="match_parent">
</ListView>
And, my main fragment page is this :
public class Apps extends Fragment {
public Apps() {}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.app_activity, container, false);
ViewPager pager = (ViewPager)mRoot.findViewById(R.id.view_pager);
AppPagerAdapter appadapter = new AppPagerAdapter(getActivity());
pager.setAdapter(appadapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override
public void onPageSelected(int position) {
//Access to this position list view for add adapter
new Loading().execute; //async task to get data and add to list view from this pager
}
#Override
public void onPageScrollStateChanged(int state) {}
});
}
}
Now, How can I access this view on screen page for adding data to this page?
I want to add data to listview of page that is selected.
Please help me .
if your viewpager have 4 fragments: A,B,C,D. And you are open fragment A. Then Fragment B and D will be create automatically by Viewpager.
And if you want to add data to listView. Let see this method:
#Override
public Object instantiateItem(ViewGroup container, int position) {
View viewItem = inflater.inflate(R.layout.pager_layout, container, false);
ListView listView = (ListView) viewItem.findViewById(R.id.list);
}
What is
int position?
It is the Page that you selected - Openning.
Your above code will create 10 Page in ViewPager, each Page have the ListView. If you want to add data to this, only write more code in method
instantiateItem()

Simple fragmented tabhost in android

I am trying to implement fragment-Tabhost in android
MainActivity.java
public class MainActivity extends Activity {
// Declare Tab Variable
ActionBar.Tab Tab1, Tab2;
Fragment fragmentTab2 = new FragmentTab2();
//Fragment fragmentTab3 = new FragmentTab3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Tab1");
//Tab2 = actionBar.newTab().setText("Tab2");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(fragmentTab2));
//Tab2.setTabListener(new TabListener(fragmentTab3));
// Add tabs to actionbar
actionBar.addTab(Tab1);
//actionBar.addTab(Tab2);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FragmentTab2.java
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
return rootView;
}
}
FragmentTab3.java
public class FragmentTab3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);
return rootView;
}
}
At present just one tab with one activity is displaying
What i am trying to do ::
click on tab1(first time) - - - - > FragmentTab2.java must display
Click on tab1(second time) - - - - > FragmentTab3.java must display
click on tab1(third time)- - - - > FragmentTab2.java must display again
This cycle must keep on repeating itself
What code changes should i need to make ?
Any IDEAS ?
I got it to work, you still need to make some adjustments, but it will get you started.
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements Notify, TabListener {
ActionBar.Tab tab1;
ActionBar actionBar;
int count = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.container, new FragmentTab2()).commit();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = actionBar.newTab().setText("Tab1");
tab1.setTabListener(this);
actionBar.addTab(tab1);
}
//Callback
#Override
public void notifyTabListener() {
count++;
Tab tab = actionBar.newTab().setText("Tab" + count);
tab.setTabListener(this);
actionBar.addTab(tab);
}
//Tablistener
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.container, new FragmentTab2());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(new FragmentTab2(), "Tab" + count);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Notify callback:
public interface Notify {
public void notifyTabListener();
}
FragmentTab2:
public class FragmentTab2 extends Fragment implements OnClickListener {
Notify mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.f2, container, false);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout2);
layout.setOnClickListener(this);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (MainActivity) activity;
}
#Override
public void onClick(View v) {
mCallback.notifyTabListener();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
f2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:text="Fragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You need to implement TabListener and set to Tab1.setTabListener().
When onTabSelected(), repeating replace fragment1 or fragment2.

Categories