How make click button in toolbar from different fragment in ViewPager? - android

I have activity,which have 5 fragments in ViewPager and in toolbar I have made one button and I want to perform click operation on button differently for selected tab fragment.I have have:
usertextView_done= (TextView) getActivity().findViewById(R.id.actionbar_tv_icon_done);
But it creates the single instance for all fragment or all tab.

If this toast appears from every fragment when clicked, then you can do following.
-- in your activity
public void calledFromFragment(String tag)
{
if(tag.equalsIgnorecase("fragment-1-tag")
{
// TODO : for fragment 1
}
else if(tag.equalsIgnorecase("fragment-2-tag"){
// TODO : for fragment 2
}
.
.
and so on
}
---- in your fragment
textView_done.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) {
((Activity)context).calledFromFragment("fragment-1-tag");
});
do this for each fragment and let me know.

I am assuming that the button and toolbar exist in the parent activity.
So here is a simple way to do it:
The idea is to create a static integer in the activity and update it in the fragments with its respective number, this way you can keep track of which fragment is currently visible.
Example:
//in activity class
public static int CURRENT_FRAGMENT = 1; //set this to your first fragment that is being viewed
Now, you have to update the integer from each fragment that is resumed.
//in each fragment add this code
#Override
public void onResume(){
ParentActivity.CURRENT_FRAGMENT = 2; //in case you're in fragment 2
}
And finally in your activity, add this:
//in actvity class
button .setOnClickListener(new OnClickListener() {
if(CURRENT_FRAGMENT ==1 ){
//do things for fragment 1
} else if (CURRENT_FRAGMMENT ==2 ){
//do things for fragment 2
}
etc...
}

Related

Fragment not attached to Activity when back pressed

I have an implementation of fragment as explained here. I have expanded the BaseFragment class to handle navigation icon onClickListener. The code for that looks like this,
private void onBackButtonPressed(int tag)
{
switch (tag)
{
case Global.DISPLAY_STORE:
{
setTitle("Loyalty Cards",Color.BLACK);
setToolBar(getResources().getColor(R.color.white), Global.ADD_CARD,R.drawable.add_round_btn);
break;
}
case Global.ADD_CARD:
{
setTitle("Wallet", Color.WHITE);
setToolBar(getResources().getColor(R.color.colorPrimary), Global.DISPLAY_STORE,R.drawable.icon_shopping);
getFragmentManager().popBackStack();
break;
}
case Global.CARD_DETAILS:
{
setTitle("Loyalty Cards",Color.BLACK);
setToolBar(getResources().getColor(R.color.white), Global.ADD_CARD,R.drawable.add_round_btn);
getFragmentManager().popBackStack();
break;
}
}
}
I am using this block of code to change the ToolBar icons and colors when back button is pressed.This code resides in BaseFragment.
Here is how I implement the code to handle back press,
I have my fragment extending the BaseFragment
public class CardDetailsFragment extends BaseFragment
Now inside the BaseFragment onCreate I have this code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity = (MainActivity) getActivity();
ImageButton righBarButton = (ImageButton) mainActivity.getToolbar().findViewById(R.id.btn_ToolBarRightBtn);
righBarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRighBarButtonClicked(Integer.parseInt(v.getTag().toString()));
}
});
mainActivity.getToolbar().setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackButtonPressed(BACK_BUTTON_TAG);
}
});
getFragmentManager().addOnBackStackChangedListener(this);
shouldDisplayHomeUp();
}
By this every fragments back button press and the right bar button item click in toolbar are handled.
Consider the scenario I have three fragments A , B and C.
From Fragment A I open Fragment B and Then Fragment C. Now From fragment C I click the back button to reach fragment B. The back button event is handled by above code and it works fine.
Now from Fragment B, I click the back button to reach Fragment A. But when I click back button I am getting exception
java.lang.IllegalStateException: Fragment CardDetailsFragment{d8b35b5} not attached to Activity
at android.support.v4.app.Fragment.getResources(Fragment.java:636)
here the CardDetailsFragment is the FragmentC, but I am clicking the
back button from Fragment B
The first time the user presses the back button, Fragment C is no longer necessary and thus it is detached from the activity. The problem lies in the fact that even though Fragment C is detached, it is still registered as a listener for back stack change events.
The second time the user presses the back button, your onBackStackPressed() method is called in Fragment C. When getResources() is executed, there is no activity attachment so getResources() fails.
Something like this in your fragment should fix it:
#Override
public void onDestroy() {
getFragmentManager().removeOnBackStackChangedListener(this);
super.onDestroy();
}

How can I control the activity's up button from a contained fragment?

I'm building a pretty simple app. At it's core are 2 screens:
1) list-screen: a list of items
2) detail-screen: a detailed view of an item
I used one Activity (which extends AppCompatActivity) with an Action-Bar, a Navigation-Drawer and a main-content part (a FrameLayout).
I used 2 different fragments for the 2 screens:
When opening the app I inflate the list-fragment into the main-content part.
When an item in the list is clicked I inflate the detail-fragment into the main-content part and it all works well.
On the detail-screen I want the Action-Bar to display an up-button that goes back to the list-screen.
Considering the fact that I am using fragments, rather than separate activites, how can I achieve that?
You can enable the up button each time the Detail Fragment loads, and disable it whenever any of the other Fragments load.
First define these methods in your Activity, which you can call from the Fragments in order to show/hide the up button:
public void showUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void hideUpButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
You will probably want to just enable the up button in on Resume() of the detail Fragment (MainActivity is just an example, change to the name of your Activity) .....
#Override
public void onResume() {
super.onResume();
MainActivity activity = (MainActivity)getActivity();
if (activity != null) {
activity.showUpButton();
}
}
Then in the other Fragments:
#Override
public void onResume() {
super.onResume();
MainActivity activity = (MainActivity)getActivity();
if (activity != null) {
activity.hideUpButton();
}
}
The next thing is to make the up button actually go back. First ensure that you're adding the Fragment with the up button to the back stack, and then add this to that Fragment.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Then in the Activity, override onBackPressed() and pop from the back stack if the FragmentManager has any entries:
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 1) {
fragmentManager.popBackStackImmediate();
} else {
super.onBackPressed();
}
}

Is it possible to set different actions for floating action button in differet fragments?

I am working or an app where I have 4 fragments in viewpager and floating action button (fab). When I click on fab there appear 3 subfabs. Each of them start different activities where user can search data from different fragments. Is it possible to set fab so that if I click on it while I'm in first fragment it'll open an activity for searching inside this fragment, onClick inside second - search for second and etc. The issue is that now clicking on sub fab while I'm in some fragment I can search data from another fragment too and it's a bit weird. I understand question is kinda strange, if something is unclear I'll explain further
You can make FAB button public and implement onClick listener in each fragment.
You should override setUserVisibleHint and put your code onResume so getActivity() will not return null. Fab button will have different actions in different fragments.
Here's an example, inside each fragment when you want Fab click listener:
#Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
onResume();
}
}
#Override
public void onResume()
{
super.onResume();
if (!getUserVisibleHint())
{
return;
}
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do what you want
}
});
}
You can check in onclick method of floating action button which fragment is currently opened and calling it.
Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.

Back button in fragment Android-Related

I have one fragment in which a listview is created. When the list is clicked the same list is refreshed and its child elements are loaded on the same. Could anyone please tell me how to enable the backbutton in android to get the parent list?
You can override your activity's onBackPressed() and get the fragment instance by FragmentManager, and do what you want.
Use the method onResume()
#Override
public void onResume() { // TODO Auto-generated method stub
super.onResume();
}
You have to take callback from onBackPressed of Activity to Fragment and check in Fragment if there is child elements open or not.
In Activiity
public void onBackPressed()
{
if(!fragment.onBackPressed())//onBackPressed in fragment is your own function
{
super.onBackPressed();
}
}
In Fragment
public boolean onBackPressed() //your custom onBackPressed not overrided
{
if(childListOpen)
{
//close the child list
return true;
}
else
{
// whatever to do in back pressed of list
return false;
}
}
For your simplicity, Define one static variable in your activity that track the which fragment is currently visible, like
public static fragIndex = 0;
then in your fragment oncreateView before returning view set it accordingly to fragments. like in list view fragment
MainActivity.fragIndex = 0;
and for detailed fragment
MainActivity.fragIndex = 1;
now on your activities onbackpressed method do like
if(fragIndex == 0){
//whatever you want to do.
}else if(fragIndex == 1){
// change the fragment back to list view
}

Different action for button (OnClickListener) in distinct fragment

i have a FragmentActivity with three Fragment and want to handle setOnClickListener in each of fragment with Different action, but Button return action for last fragment.
now , how possible to make Different action for button in distinct fragment?
in FragmentActivity :
#Override
public Fragment getItem(int position) {
FrameLayout frameLayout=reg_next;
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return o1.newInstance(0, "1",vpPager,ButtonNext);
case 1: // Fragment # 0 - This will show FirstFragment different title
return o2.newInstance(1, "2",vpPager,ButtonNext);
case 2: // Fragment # 0 - This will show FirstFragment different title
return o3.newInstance(2, "3");
default:
return null;
}
}
in Fragments:
{
...
ButtonNext.setOnClickListener(this);
...
}
In Fragment 1:
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Fragment Number 1",0).show();
}
In Fragment 2:
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Fragment Number 2",0).show();
}
But always return Fragment Number 2 setOnClickListener event ,Even when current fragment is first fragment (Fragment 1)
there are any way for multi-handling in distinct fragment?
In your case, I would do this:
Define onClick listener in your activity, not in your fragments. This will act like a dispatcher.
Set different ID to every button (in order to be able to distinguish them).
Bind a variable to indicate the current fragment. Every time you load a fragment (I suppose in your getItem, but I'm not sure), set your variable to something which identifies the fragment (for instance .class, or a String value).
With if/else select the action for the button depending on your "bind variable", and call a method declared in the fragment which handles the event.(for instance: buttonFragment3Clicked(View v)), declared in your third fragment.
I hope this helps!! :)

Categories

Resources