我如何为所有活动设置一个基本抽屉

Posted

技术标签:

【中文标题】我如何为所有活动设置一个基本抽屉【英文标题】:How can i setup a base drawer for all activities 【发布时间】:2018-10-23 05:16:00 【问题描述】:

我在这里阅读了很多答案,但无法做到。我希望我所有的活动都有一个抽屉。在抽屉里面我有一个ListView,它包含了抽屉应该打开的所有活动。这是抽屉的实现:

public abstract class DrawerActivity extends BaseActivity 

    private DrawerLayout drawerLayout;
    private ListView drawerList;
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_drawer_layout);
        drawerLayout = findViewById(R.id.drawer_layout);

        drawerList = findViewById(R.id.left_drawer);
        final ArrayList<String> elements = new ArrayList<>();
        elements.add("My tasks");
        elements.add("Issues");

        drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, elements));
        drawerList.setOnItemClickListener(createOnDrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        drawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                drawerLayout,         /* DrawerLayout object */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) 
            public void onDrawerClosed(View view)
            
                getSupportActionBar().setTitle("TITLE");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            

            public void onDrawerOpened(View drawerView)
            
                getSupportActionBar().setTitle("Title");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            
        ;

        drawerLayout.addDrawerListener(drawerToggle);
    

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */
    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    
        if (drawerToggle.onOptionsItemSelected(item))
            return true;

        return super.onOptionsItemSelected(item);
    

    protected abstract DrawerItemClickListener createOnDrawerItemClickListener();

    protected ListView drawerList()
    
        return drawerList;
    

    protected DrawerLayout drawerLayout()
    
        return drawerLayout;
    


这是抽屉布局xml文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_
    android:layout_>

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_
        android:layout_ />

    <!-- The navigation drawer -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_
        android:layout_
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#274"/>

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

假设我目前有两个活动,我的任务和问题,它们都扩展了DrawerActivity。如果我在问题活动中,如何通过该抽屉打开我的任务活动?

所有扩展 DrawerActivity 的活动都实现了 createOnDrawerItemClickListener(),它在内部创建了一个带有实现 DrawerActivity 的活动的布局的新片段,我很确定这是错误的。

示例实现:

@Override
protected DrawerItemClickListener createOnDrawerItemClickListener()

    return new DrawerItemClickListener(position ->
    
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, new TaskFragment()).commit();
        drawerList().setItemChecked(position, true);
        drawerLayout().closeDrawer(drawerList());
    );

还有 DrawerItemClickListener:

public class DrawerItemClickListener implements ListView.OnItemClickListener 

    private FragmentStrategy fragmentStrategy;

    public DrawerItemClickListener(final FragmentStrategy fragmentStrategy)
    
        this.fragmentStrategy = fragmentStrategy;
    

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    
        fragmentStrategy.showFragment(position);
    

    public interface FragmentStrategy 

        void showFragment(final int position);

    

我怎样才能做到这一点?

【问题讨论】:

如果您希望所有屏幕都有抽屉,最好的方法是在单个活动中使用片段,而不是在所有活动中设置抽屉。将您的活动转换为片段需要 5 分钟。 我对Android不是很熟悉,我该怎么做? 你想告诉我将活动转换为片段还是在活动中添加片段的方法? 【参考方案1】:

在您的情况下,添加片段将是最好的解决方案。

创建一个片段 BlankFragment.java

public class BlankFragment extends Fragment 

    public BlankFragment() 
        // Required empty public constructor
    

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

    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    


并创建 fragment_black.xml

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context="com.above_inc.shyam.drawer.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_
        android:layout_
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

现在替换你的方法

public boolean onNavigationItemSelected(MenuItem item) 
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Fragment fragment = null;
    if (id == R.id.nav_camera) 
        // Handle the camera action
        fragment = new BlankFragment();
     else if (id == R.id.nav_gallery) 

     else if (id == R.id.nav_slideshow) 

     else if (id == R.id.nav_manage) 

     else if (id == R.id.nav_share) 

     else if (id == R.id.nav_send) 

    

    if (fragment != null) 
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

    
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;


在您的 content_main.xml 中添加以下代码

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.above_inc.shyam.drawer.MainActivity"
    tools:showIn="@layout/app_bar_main">


    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_
        android:layout_
        />
</RelativeLayout>

您还可以在上述代码中添加更多片段到与相机相同的其他选项

【讨论】:

以上是关于我如何为所有活动设置一个基本抽屉的主要内容,如果未能解决你的问题,请参考以下文章

我如何为我的表设置一个普通的列头,里面有可扩展的部分,其中包括表的行?

我如何为 innerHTML 设置动画

导航抽屉开启新活动

我如何为固定数据表组件的单元格设置动画?

所有活动中的Android导航抽屉[重复]

想要使用片段从导航抽屉活动移动到另一个屏幕,以在所有屏幕上显示抽屉