继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Android开发笔记——侧滑Menu+Fragment框架代码(有些代码为AS自动生成) ... ..

波斯汪
关注TA
已关注
手记 364
粉丝 66
获赞 428

以下框架代码作为笔记,便于以后开发

1.侧滑Menu Fragment布局代码:

<?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="match_parent"
              android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/color_drawer_line"
        android:contentDescription="@string/app_name"/>

    <RelativeLayout
        android:id="@+id/rl_menu1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/button_menu_item_bg">

        <ImageView
            android:id="@+id/img_menu1"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_marginEnd="15dp"
            android:layout_marginStart="20dp"
            android:contentDescription="@string/app_name"
            android:scaleType="fitCenter"
            android:src="@mipmap/icon_menu_poi_alerts"/>

        <TextView
            android:id="@+id/tv_menu1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@id/img_menu1"
            android:text="@string/menu_poi_alert"
            android:textColor="@color/color_text_white"
            android:textSize="18sp"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_alignParentStart="true"
            android:gravity="center"
            android:textColor="@color/color_text_white"
            android:textSize="@dimen/text_size_larger"/>
    </RelativeLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="@dimen/margin_6"
        android:background="@color/color_drawer_line"
        android:contentDescription="@string/app_name"/>

    <RelativeLayout
        android:id="@+id/rl_menu2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/button_menu_item_bg">

        <ImageView
            android:id="@+id/img_menu2"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_centerVertical="true"
            android:layout_marginEnd="15dp"
            android:layout_marginStart="20dp"
            android:contentDescription="@string/app_name"
            android:scaleType="fitCenter"
            android:src="@mipmap/icon_menu_history"/>

        <TextView
            android:id="@+id/tv_menu2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@id/img_menu2"
            android:text="@string/menu_history"
            android:textColor="@color/color_text_white"
            android:textSize="18sp"
            />

    </RelativeLayout>

</LinearLayout>

2.侧滑Menu Fragment代码:

public class NavigationDrawerFragment extends Fragment implements View.OnClickListener {

    public static final  int    SELECT_MENU1          = 0;
    public static final  int    SELECT_MENU2          = 1;
    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * If user use the app for the first time,the drawer setting will show.
     * This tell user that there is a drawer setting
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle _mDrawerToggle;
    private DrawerLayout     _mDrawerLayout       = null;
    private View             _mDrawerFragmentView = null;
    private boolean          _mUserLearnedDrawer  = false;
    private RelativeLayout   _rlMenu1             = null;
    private RelativeLayout   _rlMenu2             = null;

    public NavigationDrawerFragment() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        _mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            ((MainActivity) getActivity())._mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_drawer, container, false);
        _rlMenu1 = contentView.findViewById(R.id.rl_menu1);
        _rlMenu2 = contentView.findViewById(R.id.rl_menu2);

        _rlMenu1.setOnClickListener(this);
        _rlMenu2.setOnClickListener(this);

        selectItem(((MainActivity) getActivity())._mCurrentSelectedPosition);//
        return contentView;
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        _mDrawerFragmentView = getActivity().findViewById(fragmentId);
        _mDrawerLayout = drawerLayout;
        _mDrawerLayout.setDrawerShadow(R.mipmap.drawer_shadow, GravityCompat.START);
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        _mDrawerToggle = new ActionBarDrawerToggle(getActivity(), _mDrawerLayout, null, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!_mUserLearnedDrawer) {
                    _mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!_mUserLearnedDrawer) {
                    _mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                _mDrawerLayout.getChildAt(0).setTranslationX(400/*You can use screen with * 4/5 to replace*/ * slideOffset);
            }
        };

        _mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                _mDrawerToggle.syncState();
            }
        });

        _mDrawerLayout.addDrawerListener(_mDrawerToggle);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, ((MainActivity) getActivity())._mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        _mDrawerToggle.onConfigurationChanged(newConfig);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rl_menu1:
                selectItem(SELECT_MENU1);
                break;
            case R.id.rl_menu2:
                selectItem(SELECT_MENU2);
                break;
        }
    }

    private void selectItem(int selected, boolean isCloseDrawer, boolean isRefresh/*after show the selected fragment and refresh data UI*/) {
        ((MainActivity) getActivity())._mCurrentSelectedPosition = selected;
        setViewStateResource(selected);
        if (_mDrawerLayout != null && isCloseDrawer) {
            _mDrawerLayout.closeDrawer(_mDrawerFragmentView);
        }
        if (getActivity() != null) {
            ((MainActivity) getActivity()).onNavigationDrawerItemSelected(selected, isRefresh);
        }
    }

    public void selectItem(int selected) {
        selectItem(selected, true, true);
    }

    private void setViewStateResource(int selected) {

        switch (selected) {
            case SELECT_MENU1:
                _rlMenu1.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_btn_login_normal));
                _rlMenu2.setBackgroundResource(R.drawable.button_menu_item_bg);
                break;
            case SELECT_MENU2:
                _rlMenu1.setBackgroundResource(R.drawable.button_menu_item_bg);
                _rlMenu2.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_btn_login_normal));
                break;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        _mDrawerLayout.removeDrawerListener(_mDrawerToggle);
    }

    private ActionBar getActionBar() {
        return ((AppCompatActivity) getActivity()).getSupportActionBar();
    }
}

3.MainActivity 布局代码:VS 生成

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- content fragment you should define by yourself -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" that's means setting from left -->
    <!-- setting fragment -->
    <fragment
        android:id="@+id/navigation_drawer"
        android:name="com.d3xlogic.facedetection.NavigationDrawerFragment"
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        tools:layout="@layout/fragment_drawer" />

</android.support.v4.widget.DrawerLayout>

4.MainActivity 代码:

public class MainActivity extends AppCompatActivity {

    private NavigationDrawerFragment _navigationDrawerFragment = null;
    private DrawerLayout     _drawerLayout             = null;
    private Fragment         _currentFragment          = null;
    private FragmentMenu1       _fragmentMenu1         = null;
    private FragmentMenu2      _fragmentMenu2          = null;
    public  int              _mCurrentSelectedPosition = NavigationDrawerFragment.SELECT_MENU1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _fragmentMenu1 = FragmentMenu1.newInstance();
        _fragmentMenu2 = FragmentMenu2.newInstance();

        setContentView(R.layout.activity_main);
        /*hide action bar*/
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        _drawerLayout = findViewById(R.id.drawer_layout);
        _navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        if (_navigationDrawerFragment.getView() != null) {
            ViewGroup.LayoutParams params = _navigationDrawerFragment.getView().getLayoutParams();
            params.width = 400/*You can use screen width * 4 / 5 to replease*/;
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            _navigationDrawerFragment.getView().setLayoutParams(params);
        }
        _navigationDrawerFragment.setUp(R.id.navigation_drawer, _drawerLayout);

    }


    /**
     * you can replace fragment by click setting item
     */
    public void onNavigationDrawerItemSelected(int selected, boolean isRefresh) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch (selected) {
            case NavigationDrawerFragment.SELECT_MENU1:
                switchContent(_fragmentMenu1, fragmentManager, "FragmentMenu1", isRefresh);
                break;
            case NavigationDrawerFragment.SELECT_MENU2:
                switchContent(_fragmentMenu2, fragmentManager, "FragmentMenu2", isRefresh);
                break;
        }
    }

    private void switchContent(BaseFragment to, FragmentManager fragmentManager, String tag, boolean isRefresh) {
        if (_currentFragment != to) {
            to.setIsRefresh(isRefresh);
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (!to.isAdded()) {
                if (_currentFragment == null) {
                    transaction.add(R.id.container, to, tag).commit();
                } else {
                    transaction.hide(_currentFragment).add(R.id.container, to).commit();
                }
            } else {
                transaction.hide(_currentFragment).show(to).commit();
            }
            _currentFragment = to;
        }
    }

}

5.FragmentMenu1 测试代码:

public class FragmentMenu1 extends Fragment {
    public static FragmentMenu1 newInstance() {
        return new FragmentMenu1();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_menu1, container, false);
        return rootView;
    }
}

原文链接:http://www.apkbus.com/blog-184446-78101.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP