导航的 BaseActivity

Posted

技术标签:

【中文标题】导航的 BaseActivity【英文标题】:BaseActivity for Navigation 【发布时间】:2016-01-05 16:51:40 【问题描述】:

我正在构建一个用于导航的基本 Activity,并且想要一些灵活的东西,因此 Activity 向 Base Activity 指示要膨胀的布局。

我有以下

public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener 

    private int mLayoutRes;

    protected void setLayout(int layoutRes) 
        mLayoutRes = layoutRes;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(mLayoutRes);

        // Layout implements toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);
        


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        // The layout implements the nav
        if (drawer != null)
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.setDrawerListener(toggle);
            toggle.syncState();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);
        

    
// Other Nav code ommitted as its too verbose

然后 Layout 从 Activity 传递如下

public class Home extends BaseActivity 

    private final String TAG = "Home";

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.setLayout(R.layout.activity_home);
        super.onCreate(savedInstanceState);
        // Other Activity code
    

有没有更好的方法来实现这一点? 也许设置一个带有内容框架的基本布局并膨胀到其中?

任何建议将不胜感激。

【问题讨论】:

从概念上讲,在基类中定义 getLayout() 并在子类中覆盖它会更好。 super.set() 不是你经常看到的。 【参考方案1】:

您可以通过 Google IO 应用程序关注 BaseActivity。只需覆盖setContentView,您就不需要setLayout

这是我的 BaseActivity

package com.vtcmobile.kqviet.activity;


public class BaseActivity extends AppCompatActivity 

private Toolbar toolbar;

private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private NavigationView navigationView;
protected Context mContext;


public NavigationView getNavigationView() 
    return navigationView;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    mContext = BaseActivity.this;



@Override
public void setContentView(int layoutResID) 
    super.setContentView(layoutResID);
    initToolbar();


private void initToolbar() 
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


private void setUpNav() 
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
    drawerLayout.setDrawerListener(drawerToggle);

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    navigationView = (NavigationView) findViewById(R.id.navigation);


    // Setting Navigation View Item Selected Listener to handle the item
    // click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() 

        public boolean onNavigationItemSelected(MenuItem menuItem) 

            // Checking if the item is in checked state or not, if not make
            // it in checked state
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            // Closing drawer on item click
            drawerLayout.closeDrawers();

            // Check to see which item was being clicked and perform
            // appropriate action
            Intent intent;
            switch (menuItem.getItemId()) 

            case R.id.xxxx:

                return true;



            
            return false;
        
    );

    // Setting the actionbarToggle to drawer layout

    // calling sync state is necessay or else your hamburger icon wont show
    // up
    drawerToggle.syncState();



@Override
public void onPostCreate(Bundle savedInstanceState) 
    super.onPostCreate(savedInstanceState);
    setUpNav();

    drawerToggle.syncState();


@Override
public void onConfigurationChanged(Configuration newConfig) 
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


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

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in androidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);





 

【讨论】:

你好@Nam Trung,很好解释,但我遇到了一些问题,最后我得到了解决方案,如果有人在工具栏中遇到同样的空指针问题,你可以参考这个链接:***.com/questions/33009469/… 【参考方案2】:

我使用 baseactivity 的膨胀布局和重用对 BaseActivity 类进行了一些更改,您可以使用以下类仅扩展到您的任何一个 Activity 类中。

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;


public class BaseActivity extends AppCompatActivity 

public Toolbar toolbar;

public DrawerLayout drawerLayout;
public ActionBarDrawerToggle drawerToggle;
public NavigationView navigationView;
public Context mContext;
public NavigationView getNavigationView() 
    return navigationView;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    mContext = BaseActivity.this;
    setContentView(R.layout.base_activity);



@Override
public void setContentView(int layoutResID) 
    DrawerLayout fullView = (DrawerLayout)getLayoutInflater().inflate(R.layout.base_activity, null);
    FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
    getLayoutInflater().inflate(layoutResID, activityContainer, true);
    super.setContentView(fullView);

    initToolbar();


private void initToolbar() 
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


private void setUpNav() 
    drawerLayout = (DrawerLayout) findViewById(R.id.activity_container);
    drawerToggle = new ActionBarDrawerToggle(BaseActivity.this, drawerLayout, R.string.app_name, R.string.app_name);
    drawerLayout.setDrawerListener(drawerToggle);

    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    navigationView = (NavigationView) findViewById(R.id.navigation);


    // Setting Navigation View Item Selected Listener to handle the item
    // click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() 

        public boolean onNavigationItemSelected(MenuItem menuItem) 

            // Checking if the item is in checked state or not, if not make
            // it in checked state
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            // Closing drawer on item click
            drawerLayout.closeDrawers();

            // Check to see which item was being clicked and perform
            // appropriate action

            Intent intent;
            switch (menuItem.getItemId()) 
                case R.id.xxxx:
                    return true;
            
            return false;
        
    );

    // Setting the actionbarToggle to drawer layout

    // calling sync state is necessay or else your hamburger icon wont show
    // up
    drawerToggle.syncState();



@Override
public void onPostCreate(Bundle savedInstanceState) 
    super.onPostCreate(savedInstanceState);
    setUpNav();

    drawerToggle.syncState();


@Override
public void onConfigurationChanged(Configuration newConfig) 
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    if (drawerToggle.onOptionsItemSelected(item))
        return true;
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_settings) 
        return true;
    
    return super.onOptionsItemSelected(item);


这是我的 base_activity.xml,

<android.support.v4.widget.DrawerLayout
android:id="@+id/activity_container"
android:layout_
android:layout_
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_
        android:layout_

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

</LinearLayout>
<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_
    android:layout_
    android:layout_gravity="start"
    />
</android.support.v4.widget.DrawerLayout>

【讨论】:

如果任何人在访问任何视图时都会出现空指针异常,我要求使用它为我工作的所有支持库版本 23.0.0。比如,编译 'com.android.support:appcompat-v7:23.0.0' 并编译 'com.android.support:design:23.0.0'【参考方案3】:

你可以参考我下面的代码,在我的基础活动中注意addContentView(这里我命名为NavigationDrawerActivity

基础活动:

public class NavigationDrawerActivity extends AppCompatActivity 
    private DrawerLayout mDrawerLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_drawer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerLayout.setDrawerListener(toggle);
        toggle.syncState();
    
    /**
     * called in extending activities instead of setContentView...
     *
     * @param layoutId The content Layout Id of extending activities
     */
    public void addContentView(int layoutId) 
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(layoutId, null, false);
        mDrawerLayout.addView(contentView, 0);
     

然后在其他活动中,例如MainActivity:

public class MainActivity extends NavigationDrawerActivity 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        super.addContentView(R.layout.activity_main);
    

希望这会有所帮助!

【讨论】:

感谢@BNK 这对我来说非常有效,但唯一的问题是我没有看到切换图标。相反,它总是在 ActionBar 中向我显示返回图标。你知道我们该如何解决这个问题吗? 永远不要使用这种方法【参考方案4】:

您可以在您的BaseActivity 中覆盖setContentView 并在超级调用之后初始化所有内容,或者将所有DrawerLayout 相关的东西移动到protected 方法并从BaseActivity 的每个孩子调用它,在你之后致电setContentView。我认为第一个应该很简单,从您发布的内容来看,您可以避免在 BaseActivity 中覆盖 onCreate

【讨论】:

【参考方案5】:
    Common Navigation DraweFor All Activity

    ## BaseActivity.java ##

     public class BaseActivity extends FragmentActivity 
    
        final String[] navDrawMenuItems = "My Project" , "My Project1", "MyProject2", "MyProject3" ,"MyProject4","MyProject5","MyProject6";
        final int[] navDrawMenuIcons = R.drawable.vendor,
                R.drawable.vendor,
                R.drawable.vendor,
                R.drawable.vendor,
                R.drawable.log_icon,
                R.drawable.vendor,

        ;
        public RelativeLayout mRelativeLayout;
        public FrameLayout actContent;
        public ListView navList;
        LinearLayout drawer_List;
        TextView text_emp_name;
        public MenuDrawerAdapter menuDrawerAdapter;
        public ArrayList<Vendor_Wrapper> menuDrawerList = new ArrayList<>();
        public DrawerArrowDrawable drawerArrowDrawable;
        public ImageView drawer_indicator;
        public DrawerLayout drawer_layout;
        public float offset;
        public boolean flipped;

        SharedPreferences _SP;
        SharedPreferences.Editor _EDITOR;



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

            for (int i = 0; i < navDrawMenuItems.length; i++)
            
                menuDrawerList.add(new Vendor_Wrapper(""+i,navDrawMenuItems[i], navDrawMenuIcons[0]));
            

        

        @Override
        public void setContentView(int layoutResID)

        
            mRelativeLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
            actContent = (FrameLayout) mRelativeLayout.findViewById(R.id.main);
            // set the drawer dialog_view as main content view of Activity.
            setContentView(mRelativeLayout);
            // add dialog_view of BaseActivities inside framelayout.i.e. frame_container
            getLayoutInflater().inflate(layoutResID, actContent, true);

            drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
            // =========================================
            final Resources resources = getResources();
            drawerArrowDrawable = new DrawerArrowDrawable(resources);

            drawer_indicator = (ImageView) findViewById(R.id.drawer_indicator);
            drawerArrowDrawable.setStrokeColor(resources.getColor(android.R.color.white));
            drawer_indicator.setImageDrawable(drawerArrowDrawable);
            // =========================================

            text_emp_name=(TextView)findViewById(R.id.text_emp_name) ;
            _SP = getSharedPreferences(Constants.pref_name, MODE_PRIVATE);

            text_emp_name.setText(_SP.getString("empName",""));
            drawer_List=(LinearLayout)findViewById(R.id.drawer_List);
            navList = (ListView) findViewById(R.id.drawer_List1);
            menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
            navList.setAdapter(menuDrawerAdapter);

            navList.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) 
                    Intent intent;
    //                Toast.makeText(getApplicationContext(),"position "+position,30).show();
                    Log.i(Constants.TAG,"drawer_position: "+position);
                    switch (position)
                    
                        case 0:

                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            startActivityForResult(intent,Constants.EXIT);
    //                        
                            break;

                        case 1:

                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            startActivityForResult(intent,Constants.EXIT);
    //                        drawer_indicator.performClick();

                            break;
                        case 2:
                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            startActivityForResult(intent,Constants.EXIT);
    //                        drawer_indicator.performClick();
                            break;

                        case 3:
                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            startActivityForResult(intent,Constants.EXIT);
    //                        drawer_indicator.performClick();
                            break;
                        case 4:
                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            intent.putExtra("Type","Complaints");
                            startActivityForResult(intent,Constants.EXIT);
    //                        drawer_indicator.performClick();
                            break;
                        case 5:
                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            intent.putExtra("Type","Suggestions");
                            startActivityForResult(intent,Constants.EXIT);
                            break;
                        case 6:
                            intent = new Intent(BaseActivity.this, List_of_projects.class);
                            startActivityForResult(intent,Constants.EXIT);
                            break;
                        case 7:

                            System.out.println("Logout clickedddddd ");
                            SharedPreferences.Editor editor = getSharedPreferences("my_pref", MODE_PRIVATE).edit();
                            editor.clear();
                            editor.commit();
                            setResult(Constants.EXIT);
                            finish();
                            break;

                        default:
                            break;
                    

                
            );


            initViewsandSharedPreferencesandSQLiteAdapter();
            clickToViews();

        

        public void setMenuDrawer(ArrayList<Vendor_Wrapper> menuDrawerList, String email)
        
            navList = (ListView) findViewById(R.id.drawer_List1);
            menuDrawerAdapter = new MenuDrawerAdapter(BaseActivity.this, menuDrawerList);
            navList.setAdapter(menuDrawerAdapter);
        


        public void initViewsandSharedPreferencesandSQLiteAdapter()
        

            _SP = getSharedPreferences(Constants.TAG, MODE_PRIVATE);
            _EDITOR = _SP.edit();
            drawer_indicator_LL = (LinearLayout) findViewById(R.id.drawer_indicator_LL);

        

        /**
         * Take care of popping the fragment back stack or finishing the activity
         * as appropriate.
         */
        @Override
        public void onBackPressed()
        
            super.onBackPressed();

            if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
            
                drawer_layout.closeDrawer(drawer_List);
            
            else
            
                finish();
            
        

        public void clickToViews()
        
            drawer_layout.setDrawerListener(new DrawerLayout.SimpleDrawerListener()
            
                @Override
                public void onDrawerSlide(View drawerView, float slideOffset) 
                    offset = slideOffset;
                    // Sometimes slideOffset ends up so close to but not quite 1 or 0.
                    if (slideOffset >= .995)
                    
                        flipped = true;
                        drawerArrowDrawable.setFlip(flipped);
                     else if (slideOffset <= .005)
                    
                        flipped = false;
                        drawerArrowDrawable.setFlip(flipped);
                    

                    drawerArrowDrawable.setParameter(offset);
                
            );

            drawer_indicator.setOnClickListener(new View.OnClickListener()
            
                @Override
                public void onClick(View v)
                
                    if (drawer_layout.isDrawerVisible(Gravity.RIGHT))
                    
                        drawer_layout.closeDrawer(drawer_List);
                    
                    else
                    
                        drawer_layout.openDrawer(drawer_List);
                    
                
            );

            drawer_indicator_LL.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 
                    if (drawer_layout.isDrawerVisible(Gravity.RIGHT)) 
                        drawer_layout.closeDrawer(drawer_List);
                     else 
                        drawer_layout.openDrawer(drawer_List);
                    
                
            );

        


        public void NavigationPerformClick()
        
            drawer_indicator.performClick();
        

        private class MenuDrawerAdapter extends BaseAdapter
        

            ArrayList<Vendor_Wrapper> menuDrawerList;
            Context context;


            public MenuDrawerAdapter(Context context, ArrayList<Vendor_Wrapper> menuDrawerList)
            
                super();
                this.context = context;
                this.menuDrawerList = menuDrawerList;


            

            @Override
            public int getCount()
            
                return menuDrawerList.size();
            

            @Override
            public Object getItem(int position)
            
                return position;
            

            @Override
            public long getItemId(int position)
            
                return position;
            

            @Override
            public View getView(int position, View convertView, ViewGroup parent)
            
                LayoutInflater layoutInflater = LayoutInflater.from(BaseActivity.this);
                ViewHolder viewHolder;

                if (convertView == null)
                
                    viewHolder = new ViewHolder();
                    convertView = layoutInflater.inflate(R.layout.row_menu_drawer, null);

                    viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
                    viewHolder.imgIcon = (ImageView) convertView.findViewById(R.id.img_icon);
                    viewHolder.main_RL = (RelativeLayout)convertView.findViewById(R.id.main_RL);
                    viewHolder.imgIcon.setVisibility(View.GONE);
                    convertView.setTag(viewHolder);
                
                else
                
                    viewHolder = (ViewHolder) convertView.getTag();
                

                Vendor_Wrapper menuDrawerModel = menuDrawerList.get(position);
                //## Setup Data below
                String Name = menuDrawerModel.getName();
                String id = menuDrawerModel.getId();

                viewHolder.tvTitle.setText(menuDrawerModel.getName());

    //            viewHolder.main_RL.setOnClickListener(new ClickToView(BaseActivity.this,position,id,Name));
                viewHolder.imgIcon.setImageResource(menuDrawerModel.getDrawable_icon());

                return convertView;

            

            public class ViewHolder
            
                TextView tvTitle;
                ImageView imgIcon;
                RelativeLayout main_RL;
            

        


        protected class MenuDrawerModel
        
            private String title;
            private int icon;
            public String Icon_url;

            public MenuDrawerModel(String title, int icon, String icon_url) 
                this.title = title;
                this.icon = icon;
                Icon_url = icon_url;
            

            public MenuDrawerModel(String title, int icon)
            
                super();
                this.title = title;
                this.icon = icon;
            

            public MenuDrawerModel() 
                super();
            

            public String getTitle() 
                return title;
            

            public void setTitle(String title)
            
                this.title = title;
            

            public int getIcon() 
                return icon;
            

            public void setIcon(int icon)
            
                this.icon = icon;
            

        


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) 
            super.onActivityResult(requestCode, resultCode, data);
            System.out.println("Logout onActivityResult "+resultCode);
            if(resultCode==Constants.EXIT)
            
                setResult(Constants.EXIT);
                finish();
            
        
    


    ## MainActivity.java ##

        public class MainActivity extends BaseActivity 

        @Override
        protected void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        


    ## activity_base.xml ##

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:custom="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_
        android:layout_
        android:background="@color/white">

        <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/drawer_layout"
            android:layout_
            android:layout_>

            <RelativeLayout
                android:layout_
                android:layout_>

                <include
                    android:id="@+id/header_view"
                    layout="@layout/layout_header_view"
                    android:layout_
                    android:layout_ />

                <FrameLayout
                    android:id="@+id/main"
                    android:layout_
                    android:layout_
                    android:layout_below="@+id/header_view">

                </FrameLayout>

            </RelativeLayout>

            <LinearLayout
                android:id="@+id/drawer_List"
                android:layout_
                android:layout_
                android:layout_gravity="start"
                android:layout_marginTop="50dp"
                android:background="@color/white"
                android:choiceMode="singleChoice"
                android:orientation="vertical"
                android:weightSum="10">

                <LinearLayout
                    android:layout_
                    android:layout_
                    android:layout_weight="3"
                    android:background="@drawable/bagroundg"
                    android:orientation="vertical"
                    android:visibility="gone"
                    android:weightSum="5">


                </LinearLayout>

                <ListView
                    android:id="@+id/drawer_List1"
                    android:layout_
                    android:layout_
                    android:layout_gravity="start"
                    android:background="@color/white"
                    android:choiceMode="singleChoice" />
            </LinearLayout>

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

    </RelativeLayout>


    ## activity_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"
        android:layout_
        android:layout_>

        <LinearLayout
            android:layout_
            android:layout_>


            <TextView
                android:layout_
                android:layout_
                android:gravity="center"
                android:text="Hello World!"
                android:textSize="30dp" />


        </LinearLayout>
    </RelativeLayout>


public class Vendor_Wrapper

    private String id;

    public Vendor_Wrapper(String id, String name, int drawable_icon)
    

        this.id = id;
        Name = name;
        this.drawable_icon = drawable_icon;
    

    private String Name;
    private String contact_no;
    private String Email_id;
    private String Address;
    private String img;
    private String PAY_MODE;
    private String min;
    private String max;
    private String imgs;

    private int drawable_icon;

    public int getDrawable_icon() 
        return drawable_icon;
    

    public void setDrawable_icon(int drawable_icon) 
        this.drawable_icon = drawable_icon;
    





    public String getEmail_id() 
        return Email_id;
    

    public void setEmail_id(String email_id) 
        Email_id = email_id;
    

    public String getId() 
        return id;
    

    public void setId(String id) 
        this.id = id;
    

    public String getName() 
        return Name;
    

    public void setName(String name) 
        Name = name;
    

    public String getContact_no() 
        return contact_no;
    

    public void setContact_no(String contact_no) 
        this.contact_no = contact_no;
    

    public String getAddress() 
        return Address;
    

    public void setAddress(String address) 
        Address = address;
    

    public String getImg() 
        return img;
    

    public void setImg(String img) 
        this.img = img;
    

    public String getPAY_MODE() 
        return PAY_MODE;
    

    public void setPAY_MODE(String PAY_MODE) 
        this.PAY_MODE = PAY_MODE;
    

    public String getMin() 
        return min;
    

    public void setMin(String min) 
        this.min = min;
    

    public String getMax() 
        return max;
    

    public void setMax(String max) 
        this.max = max;
    

    public String getImgs() 
        return imgs;
    

    public void setImgs(String imgs) 
        this.imgs = imgs;
    




    public Vendor_Wrapper(String id, String name, String contact_no, String email_id, String address, String img, String PAY_MODE, String min, String max, String imgs) 
        this.id = id;
        Name = name;
        this.contact_no = contact_no;
        Email_id = email_id;
        Address = address;
        this.img = img;
        this.PAY_MODE = PAY_MODE;
        this.min = min;
        this.max = max;
        this.imgs = imgs;
    



【讨论】:

这将帮助您在不添加到所有活动的情况下使用通用导航抽屉 看起来不错,很干净将调查将我当前的解决方案换成这个! 您可以从此链接下载项目github.com/Rishisahu/BaseActivityConcept【参考方案6】:

这是我实现 BaseActivity 的示例,我发现我的做法不同,它对我有用。

我的基本活动

public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener


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



public boolean onNavigationItemSelected(MenuItem item) 
    // Handle navigation view item clicks here.

    int id = item.getItemId();
    //swap this to a switch statement

    if (id == R.id.nav_newgame) 
        // Start new game

        Log.e("Base","new Game");
     else if (id == R.id.nav_players) 

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

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

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

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

    

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


任何共享同一个导航抽屉的活动

public class MainActivity extends BaseActivity
     

         NavigationView navigationView;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


在您的基础活动中允许使用一个动态导航抽屉,从而省去了一遍又一遍地编写代码的麻烦。此外,您可以覆盖 Base Activity 的 Nav Drawer,并针对不同情况生成不同的结果。

【讨论】:

以上是关于导航的 BaseActivity的主要内容,如果未能解决你的问题,请参考以下文章

使用底部导航栏导航回页面时颤动通过底部导航栏选择的索引

微信小程序页面导航详解

TabBarViewController 的导航栏覆盖来自导航控制器的导航栏

如何同时使用导航抽屉和底部导航 - 导航架构组件

高德导航怎么用 怎样使用高德地图进行导航

导航架构组件 - 新资源对话框没有导航图的导航资源类型