今天告诉大家怎样我们知道使用自定义导航。
学过IOS开发就告诉系统本身对UINavigationController导航,使用很简单和方便。
android 定义导航如下。
1.这个类继承了AppCompatAcitity类,并且跳转到ScenesFragment。
/** * 点击了“场景”按钮 */ private void click_scenes_Btn() { // 实例化Fragment页面 ScenesFragment Scenes= new ScenesFragment(); // 得到Fragment事务管理器 FragmentTransaction fragmentTransaction = this .getSupportFragmentManager().beginTransaction(); // 替换当前的页面 fragmentTransaction.replace(R.id.frame_content, Scenes); // 事务管理提交 fragmentTransaction.commit(); // 改变选中状态 }
2.ScenesFragment继承了Fragment 类。
getFragmentManager() .beginTransaction() .addToBackStack(null) //将当前fragment加入到返回栈中 .replace(R.id.frame_content, new ScenesMain()).commit();
3.这个类继承了Fragment类,返回到ScenesFragment类
。
// getActivity().onBackPressed(); getFragmentManager().popBackStack();//把这个类移出栈。
4.这里就是自定义导航栏如下。
(1)xml就是导航栏的布局。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/white" android:minHeight="?attr/actionBarSize"> <TextView android:id="@+id/title_sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:text="" android:textColor="@color/navigation" android:textSize="20sp" android:textStyle="bold" /> </android.support.v7.widget.Toolbar> <TextView android:layout_width="match_parent" android:background="@android:color/darker_gray" android:layout_height="1dp"/> </LinearLayout>
(2)实现导航栏的代码。
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view= inflater.inflate(R.layout.scenes_main,null); mToolbar = (Toolbar)view.findViewById(R.id.toolbar); mToolbar.setTitle(""); ( (AppCompatActivity)getActivity()).setSupportActionBar(mToolbar); mToolbar.setBackgroundResource(R.color.navigation); TextView tv = (TextView) mToolbar.findViewById(R.id.title_sub); tv.setText(R.string.sleep_scene); //居中的标题。 int white = getResources().getColor(R.color.white_80); tv.setTextColor(white); //返回按键 Drawable upArrow = getContext().getDrawable(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material); upArrow.setColorFilter(white, PorterDuff.Mode.SRC_ATOP); ( (AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow); //关键下面两句话,设置了回退按钮,及点击事件的效果 ( (AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getActivity().onBackPressed(); getFragmentManager().popBackStack(); } }); return view; }