vendredi 29 mai 2015

setHomeButtonEnabled on toolbar in a fragment

Android studio 1.3
com.android.support:appcompat-v7:22.1.1

Hello,

I am using the new toolbar and displaying in my fragment. However, I want to be able to navigate back to the previous fragment by having the setHomeButtonEnabled(true). However, in my fragment in the onCreateView there is no such function. This works in the Activity, but doesn't work in the fragment.

Is there anyway to have the toolbar display the setHomeButtonEnabled so that an arrow is displayed so the user can nagivate back.

public class FileTransferFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_file_transfer, container, false);

        final Toolbar toolbar = (Toolbar)view.findViewById(R.id.app_bar);
        AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
        appCompatActivity.setSupportActionBar(toolbar);

    /* TRIED THIS BUT DIDN'T WORK */
        appCompatActivity.getActionBar().setHomeButtonEnabled(true);
        appCompatActivity.getActionBar().setDisplayHomeAsUpEnabled(true);
        return view;
    }
}

In my Activity I am extending the AppCompatActivity and using appcompat-v7:22.1.1

public class FileTransferActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_transfer);

        if(savedInstanceState == null) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.fragment_container,
                    FileTransferFragment.getFileTransferFragment(1234), "FileTransferFragment");
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            fragmentTransaction.commit();
        }
    }
}

As you can see on the image there is no arraw on the left of the toolbar to allow the user to nagivate back. enter image description here

Aucun commentaire:

Enregistrer un commentaire