将抽屉布局添加到 Android 中的现有地图片段

Add a Drawer Layout to existing Map Fragment in Android

我的 Activity 中已有一个可用的地图片段。

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        tools:context=".MapsActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"

        android:layout_alignParentTop="true">



        <android.support.design.widget.FloatingActionButton
            android:id="@+id/add"
            android:onClick="locate_me"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginTop="360dp"
            android:layout_marginRight="16dp"
            android:layout_marginLeft="16dp"
            android:clickable="true"
            android:src="@drawable/tick"
            app:backgroundTint="#000"
            android:layout_gravity="right|end"
            app:layout_anchorGravity="right|end"/>





        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:onClick="locate_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:clickable="true"
            android:src="@drawable/mylocation"
            app:backgroundTint="#000000"
            android:layout_gravity="bottom|end"
            app:layout_anchorGravity="right|end"/>

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

我想为这个现有的 Activity 添加一个抽屉布局。我已经尝试了很多,但无法让它发挥作用。我也试过MapView。你能给我一些指示吗?谢谢

所以这很简单这是一个 gist,所有代码都在下面。

我的依赖部分 build.gradle :

 dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.google.android.gms:play-services:7.8.0'
    compile 'com.android.support:design:23.0.0'
}

XML 我的 AppCompatActivity 文件,其中包括抽屉布局和 SupportMapFragment,因为我在这个项目中使用 appcompat-v7:

<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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
            <fragment 
                 android:name="com.google.android.gms.maps.SupportMapFragment"
                 android:id="@+id/map"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"/>

             <android.support.design.widget.FloatingActionButton
                android:id="@+id/add"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_margin="16dp"
                android:clickable="true"
                android:src="@drawable/ic_maps_navigation"
                app:backgroundTint="#777"
                android:layout_gravity="bottom|end"/>

        </FrameLayout>

        <FrameLayout
            android:id="@+id/nav_container"
            android:layout_gravity="start"
            android:layout_width="240dp"
            android:layout_height="fill_parent"/>

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

</RelativeLayout>

那我有一个activity:

 package com.test.mapdrawer;

 import android.content.res.Configuration;
 import android.os.Bundle;
 import android.support.v4.widget.DrawerLayout;
 import android.support.v7.app.ActionBarDrawerToggle;
 import android.support.v7.app.AppCompatActivity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;

 public class MainActivity extends AppCompatActivity implements DrawerFragment.NavCallback  {

    private DrawerLayout drawer;
    private ActionBarDrawerToggle mDrawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawer = (DrawerLayout) findViewById(R.id.drawer);

        setupDrawerLayout();

        if(savedInstanceState == null) {
         /*
            Load the fragment for the drawer
         */
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.nav_container, DrawerFragment.newInstance(), "Drawer")
                .commit();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.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) {
        // 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();

        // Handle the drawer Actions
        if(mDrawerToggle.onOptionsItemSelected(item)){
            return true;
        }

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

         return super.onOptionsItemSelected(item);
     }

     private void setupDrawerLayout(){

         // Instantiate the Drawer Toggle
         mDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.string.app_name, R.string.app_name){

            @Override
            public void onDrawerOpened(View drawerView) {
                 super.onDrawerOpened(drawerView);
                 invalidateOptionsMenu();
                  getSupportActionBar().setTitle(getString(R.string.app_name));
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                 super.onDrawerClosed(drawerView);
                 invalidateOptionsMenu();
                 getSupportActionBar().setTitle(getString(R.string.app_name));
            }
         };

         // Set the Toggle on the Drawer, And tell the Action Bar Up Icon to show
         drawer.setDrawerListener(mDrawerToggle);
         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         getSupportActionBar().setHomeButtonEnabled(true);
     }

     @Override
     public void onNavSelected(int position) {
           Toast.makeText(this, "Selected item: "+ position + " from nav", Toast.LENGTH_SHORT).show();
     }
 }

最后是地图项目的典型清单:

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.test.mapdrawer" >

     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="<YOUR_MAPS_API_KEY_HERE>"/>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

 </manifest>

然后您要创建并填充导航抽屉片段:

 package com.test.mapdrawer;

 import android.app.Activity;
 import android.content.Context;
 import android.os.Bundle;
 import android.support.annotation.Nullable;
 import android.support.v4.app.Fragment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;

 public class DrawerFragment extends Fragment {


     private static final String [] NAV_ITEMS = {"Home", "Nav Item 2", " Nav Item 3", "Nav Item 4"};
     private ListView mListView;
     private NavCallback mCallback;

     public interface NavCallback{
         void onNavSelected(int position);
     }

    /**
     * Create a static method to return this fragment
     * @return - this fragment
     */
    public static DrawerFragment newInstance(){
        return new DrawerFragment();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

       mCallback = (MainActivity) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.drawer_fragment, container, false);

        /*
            You can really use anything you want here but for simplicity lest assume ListView
         */
        mListView = (ListView) view.findViewById(R.id.listViewNav);
        mListView.setOnItemClickListener(ListListener);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Simple adapter, Also this is for simplicity and adapter can be used
        mListView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, NAV_ITEMS));

    }

    private final AdapterView.OnItemClickListener ListListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mCallback.onNavSelected(position);
        }
    };
}

其中有布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="@android:color/black">
    <ListView
        android:id="@+id/listViewNav"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

请注意,我已为此更改更新了 2 个文件并添加了 2 个

  1. MainActivity -> 现在实现接口并且 onCreate 包含加载片段的逻辑
  2. activity_main.xml -> 抽屉的 FrameLayout 背景已删除
  3. 新抽屉片段
  4. 新建drawer_fragment.xml

此外,要点已更新以反映这些更改,编码愉快!