How to hide item from the MainActivity toolbar in a fragment - java

In my application I have Toolbar in the MainActivity and inside the MainActivity I have a ViewPager to show 4 fragment.
The toolbar contains some images (button).
I want in one of these fragments to hide the image from the toolbar.
I wrote the code below, but it hides the image in all the fragments.
My code:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
troy.setVisibility(View.GONE);
}
}, 50);
}
}
I want to hide it just in my current fragment, not all of them.
How can I do it?

You can use addOnPageChangeListener() of your ViewPager
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) { // Condition may vary according to your needs...
troy.setVisibility(View.GONE);
} else {
troy.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Related

Prevent repeating of items when i back to fragment

In my application , I have ViewPager containing 3 fragments (Home , Profile and More)
Home Fragment contain RecyclerView
when i navigate from Home Fragment to Profile Fragment or More Fragment, it work like expected.
But when i navigate back to Home Fragment , items in RecyclerView duplicate...
And when i navigate again and back , it duplicate again
Here is my MainActivity.java Code:
public class MainActivity extends AppCompatActivity {
TabLayout mainTabLayout;
ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainTabLayout = findViewById(R.id.main_tablayout);
mainViewPager = findViewById(R.id.main_viewpager);
mainTabLayout.setupWithViewPager(mainViewPager);
//to put mainTabLayout Icons...
MainTabLayoutIcons();
}
//to Change MainLayout Icons...
private void MainTabLayoutIcons() {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// add fragments to the adapter
adapter.addFragment(new Home());
adapter.addFragment(new MyActivity());
adapter.addFragment(new More());
mainViewPager.setOffscreenPageLimit(0);
mainViewPager.setAdapter(adapter);
// Select Home tab as default tab on startup
mainViewPager.setCurrentItem(0);
mainTabLayout.getTabAt(0).select();
// Set tabs Initial icons
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
/* tabSelectedListener to change the icon color once it is selected
// and change it back once another tab is selected */
mainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 1) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 2) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_black);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//no need for it
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//no need for it
}
});
}
}
and here is ViewPagerAdapter Code:
//Adapter for mainActivity ...
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
}
and here is first Fragment Home.java Code:
public class Home extends Fragment {
View v;
public SwipeRefreshLayout mSwipeRefreshLayout;
public RecyclerView mainRecyclerView;
private LinearLayoutManager linearLayoutManager;
public final List<MyActivityModel> mainPosts = new ArrayList<>();
private PostAdapter mAdapter;
public Home() {
/*Required Empty Constructor... */
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle bundle) {
v = layoutInflater.inflate(R.layout.fragment_home, container, false);
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.mainSwipeRefresh);
mainRecyclerView = (RecyclerView) v.findViewById(R.id.MainRecyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity());
mainRecyclerView.setLayoutFrozen(true);
mainRecyclerView.setNestedScrollingEnabled(false);
mainRecyclerView.setLayoutManager(linearLayoutManager);
mAdapter = new PostAdapter(mainPosts);
mainRecyclerView.setAdapter(mAdapter);
Swipe();
LoadPosts();
return v;
}
/**
* -----------------TODO: to load posts in Home RecyclerView...----------------
*/
public void LoadPosts() {
Query database = FirebaseDatabase.getInstance().getReference().child("Posts");
database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
if (snapshot.exists()) {
MyActivityModel post = snapshot.getValue(MyActivityModel.class);
mainPosts.add(0, post);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void Swipe() {
//to refresh page after swipe
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mainPosts.clear();
LoadPosts();
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(v.getContext(),"Refreshed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
}, 500);
}
});
}
}
and this is an image showing item reeating
Anyone can help me how to prevent this duplication...
You may need to use FragmentPagerAdapter instead of FragmentStatePagerAdapter. Also, set mainRecyclerView.setLayoutFrozen(true); to false because, it will stop everything in recyclerView.
When you need to use FragmentPagerAdapter?
FragmentStatePagerAdapter is more useful when there are a large number
of pages, working more like a list view. When pages are not visible to
the user, their entire fragment may be destroyed, only keeping the
saved state of that fragment. This allows the pager to hold on to
much less memory associated with each visited page as compared to
FragmentPagerAdapter at the cost of potentially more overhead when
switching between pages.
Example of FragmentPagerAdapter:
class viewpager_class extends FragmentPagerAdapter {
int tabcount;
public viewpager_class(#NonNull FragmentManager fm, int tab_count) {
super(fm, tab_count);
this.tabcount = tab_count;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment1 fragment1 = new Fragment1 ();
return todayBAFragment;
case 1:
Fragment2 fragment2 = new Fragment2 ();
return todayReminderDue;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return currentTransaction;
default:
return null;
}
}
#Override
public int getCount() {
return tabcount;
}
}
Also, set adapter into ViewPager wherever you want show viewPager:
//set adapter into viewpager
viewpager_class viewpagerClass = new viewpager_class(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewpagerClass);
viewPager.setOffscreenPageLimit(2);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

onPageListener Is Not Working

I need some help with setting up the position of the Fragments in order for it to work with the the onPageListener so I can set the visibility of certain views. As I am new, I am rather unsure on how to do this. Thank you for your time and effort.
MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//need some help here//
if(position == 1) {
drawerGrid.setVisibility(View.VISIBLE);
} else {
drawerGrid.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Fragments.java
public class Fragments extends FragmentPagerAdapter {
public Fragments(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //need some help here//
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
try this:
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
drawerGrid.setVisibility(View.GONE);
break;
case 1:
drawerGrid.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
use it like:
ViewPager.addOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
viewpager.post(new Runnable()
{
#Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});

ListView OnItemClickListener not being triggered in bottom sheet

I have created a bottom sheet using the newly updated support library. Basically, whenever an item in my recyclerview is long-clicked, a bottom sheet is shown (containing a linearlayout which contains a listview). But whenever I tap the items in the listview nothing happens. I added toasts and it is never triggered when I tap on the sheet items. Any ideas? Thanks in advance!
Here is the listview initialization method:
public void initSheet() {
bottomSheet = findViewById(R.id.list_sheet);
ListAdapter adapter = new ListAdapter(this, R.layout.custom_sheet_row, getSheetInfo(), "Sheet");
list = (ListView) findViewById(R.id.list_sheet_list);
list.setAdapter(adapter);
behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setHideable(true);
}
Here is the recyclerview long click:
#Override
public void onLongClick(View view, int position) {
final String itemText = ((TextView) view.findViewById(R.id.textRow)).getText().toString();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ListActivity.this, "sdjakfjs", Toast.LENGTH_SHORT).show();
switch (position) {
case 0:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_TEXT, itemText);
startActivity(Intent.createChooser(sharingIntent, "Share the item"));
break;
case 1:
final ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("New", itemText));
break;
case 2:
editText(itemText, position);
break;
case 3:
listAdapter.deleteItem(position);
break;
}
behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
try this.
implement custom clicklistener it will work pefectly.
// creating interface to handle clicks for Recycler view items
public interface ClickListener
{
void onClick(View view,int position);
void onLongClick(View view,int position);
}
public static class CustomRecyclerTouchListener implements RecyclerView.OnItemTouchListener
{
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public CustomRecyclerTouchListener(Context context,final RecyclerView recyclerView,final MainActivity.ClickListener clickListener)
{
this.clickListener=clickListener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener()
{
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener !=null)
{
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child=recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
if(child!=null && clickListener!=null && gestureDetector.onTouchEvent(motionEvent))
{
clickListener.onClick(child,recyclerView.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
}
}
Then implement like this.
recyclerView.addOnItemTouchListener(new CustomRecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
User user=users.get(position);
Toast.makeText(MainActivity.this,user.getName()+" is clicked",Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
User user=users.get(position);
Toast.makeText(MainActivity.this,user.getName()+" is long clicked",Toast.LENGTH_SHORT).show();
}
}));
For more details refer here:- http://coderzpassion.com/android-working-with-recycler-view/
Ok, what I ended up doing was creating 4 textviews inside of the linear layout instead of using the listview. Then I just added an onclick listener for all of the textviews to do their respective commands

Remove a FAB when a Fragment goes to backstack

I have seen a lot of answers but doesn't seems to find one. I am using new FAB in one of my fragments and want to remove it when that particular fragment goes to backstack, but I am not sure which method in fragment gets called when it is added to back stack and replaced by other fragment.
Following methods were called whenever the Fragment is replaced or added to backstack
1) onPause()
2) onStop()
3) onDestroyView()
call your FAB removing method in any one of the above methods in your Fragment.
http://developer.android.com/guide/components/fragments.html#Creating
Here is my suggestion -
First, add the animation code and backstack listener in your Activity:
public class MainActivity extends AppCompatActivity
implements FragmentManager.OnBackStackChangedListener {
private FloatingActionButton mFab;
private Animation mShowFab;
private Animation mHideFab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().addOnBackStackChangedListener(this);
mShowFab = AnimationUtils.makeInAnimation(this, false);
mShowFab.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationStart(Animation animation) {
mFab.setVisibility(View.VISIBLE);
}
});
mHideFab = AnimationUtils.makeOutAnimation(this, true);
mHideFab.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
mFab.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationStart(Animation animation) {
}
});
}
public void showFab(boolean show) {
boolean visible = mFab.isShown();
if (show) {
if (!visible)
mFab.startAnimation(mShowFab);
} else {
if (visible)
mFab.startAnimation(mHideFab);
}
}
And then - depending on backstack depth - show or hide the FAB:
#Override
public void onBackStackChanged() {
showFab(getSupportFragmentManager().getBackStackEntryCount() > 0);
}

Viewpager setCurrentItem() doesn't update onPageSelected()

When I swipe between questions, it loads current page number correctly
BUT when I use next button, first click doesnt loads pagenumber ( I mean onPageSelected() doesnt work.) second and other clicks loads content but it loads 1 page previous.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
mPager.setAdapter(mAdapter);
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
tv.setText( mPager.getCurrentItem()+"");
}
};
mPager.setOnPageChangeListener(pageChangeListener);
Question.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(getItem(+1));
}
}
private int getItem(int i) {
int a = mPager.getCurrentItem();
i += a;
return i;
}
});
Why not just doing this in your listener:
mPager.setCurrentItem(mPager.getCurrentItem() + 1);

Categories

Resources