Fragment Navigation Implementation

I have a MainActivity that contains a FragmentA. When I click FragmentA this happens:

getFragmentManager().beginTransaction().replace(R.id.container,new PrefFragment()).addToBackStack("back").commit();

      

I have this in my manifest:

<activity>
<meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myfirstapp.MainActivity" />
</activity>

      

and this is in MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_head_sound);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new FragmentA)
                .commit();
    }
    getActionBar().setDisplayHomeAsUpEnabled(true);

}

      

But navigation on the Up button is always visible.

FragmentB contains this code:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        switch (id)
        {
            case android.R.id.home:
                getFragmentManager().popBackStack();
                Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();

                break;
        }
        return super.onOptionsItemSelected(item);



    }

      

This code will not run. I need to implement Up Navigation in FragmentB only. How can i do this?

+3


source to share


1 answer


As far as I understand, the navbar should only work in FragmentB, whereas when FragmentA is displayed upwards, the navbar will be hidden. If so, in the Office, delete getActionBar().setDisplayHomeAsUpEnabled(true);

from onCreate

.

Also you should return true when you handle the menu click and move onOptionsItemSelected (MenuItem) to the Activity, since the android.R.id.home android menu click is only delivered to the Activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getFragmentManager().popBackStack();
            Toast.makeText(getActivity(),"CLick",Toast.LENGTH_SHORT).show();
            return true; //Notice you must returning true here

        default:
            return super.onOptionsItemSelected(item);
    }
}

      

In FragmentA



@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    a.getActionBar().setDisplayHomeAsUpEnabled(false);
}

      

In FragmentB

@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    a.getActionBar().setDisplayHomeAsUpEnabled(true);
}

      

+2


source







All Articles