Android studio 1.3
com.android.support:appcompat-v7:22.1.1
你好,
我正在使用新的工具栏并在我的片段中显示。然而,我希望能够通过 setHomeButtonEnabled(true)
返回到上一个片段。但是,在我的片段的onCreateView中没有这样的函数。这在Activity中可以工作,但在片段中不起作用。
有没有办法使工具栏显示setHomeButtonEnabled,以便用户可以看到箭头并返回。
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;
}
}
在我的Activity中,我扩展了AppCompatActivity
并使用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();
}
}
}
如您所见,工具栏左侧没有箭头以允许用户返回。
![enter image description here](https://istack.dev59.com/hFqRg.webp)