导航抽屉打开空白活动

时间:2015-02-22 14:51:51

标签: android android-fragments android-activity navigation-drawer

我正在开发一个使用导航抽屉的应用程序。我点击按钮调用导航抽屉。但问题是,当我按下按钮时,我得到空白页面,我的第一个项目未被选为主要项目,即使我将其指示为主要项目。

这是我的代码,这是我的mainActivity:

    package sightsOfAlmaty;

import sightsOfAlmaty.NavDrawerListAdapter;
import sightsOfAlmaty.NavDrawerItem;

import java.util.ArrayList;

import com.example.new1.R;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;

public class sightsOfAlmaty extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
protected ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private static boolean isLaunch = true;

// nav drawer title
private CharSequence mDrawerTitle;

// used to store app title
protected CharSequence mTitle;

// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;

private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
protected FrameLayout frameLayout;

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

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    // nav drawer icons from resources
    navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);
    frameLayout = (FrameLayout)findViewById(R.id.frame_container);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Find People
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    // Photos
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    // Communities, Will add a counter here
    //navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
    // Pages
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
    // What's hot, We  will add a counter here
//  navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));


    // Recycle the typed array
    navMenuIcons.recycle();
    // setting the nav drawer list adapter
            adapter = new NavDrawerListAdapter(getApplicationContext(),
                    navDrawerItems);

            mDrawerList.setAdapter(adapter);
            mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

            // enabling action bar app icon and behaving it as toggle button
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            //R.drawable.ic_drawer, //nav menu toggle icon
            R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            invalidateOptionsMenu();
            super.onDrawerClosed(view);

        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            invalidateOptionsMenu();
            super.onDrawerOpened(drawerView);

        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /**
     * As we are calling BaseActivity from manifest file and this base activity is intended just to add navigation drawer in our app.
     * We have to open some activity with layout on launch. So we are checking if this BaseActivity is called first time then we are opening our first activity.
     * */
    if(isLaunch){
         /**
          *Setting this flag false so that next time it will not open our first activity.
          *We have to use this flag because we are using this BaseActivity as parent activity to our other activity. 
          *In this case this base activity will always be call when any child activity will launch.
          */
        isLaunch = false;
        displayView(0);
    }
   }

   /**
     * Slide menu item click listener
    * */
    private class SlideMenuClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // display view for selected nav drawer item
        displayView(position);
      }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action bar actions click
    switch (item.getItemId()) {
    case R.id.action_settings:
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
    }

   /* *
     * Called when invalidateOptionsMenu() is triggered
    */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;

    Intent intent;
    switch (position) {
    case 0:
        /*intent = new Intent(this, HomeFragment.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(intent);*/
        startActivity(new Intent(this, HomeFragment.class));
        return;
    case 1:
        //fragment = new FindPeopleFragment();
        break;
    /*case 2:
        fragment = new PhotosFragment();
        break;
    case 3:
        fragment = new CommunityFragment();
        break;
    case 4:
        fragment = new PagesFragment();
        break;
    case 5:
        fragment = new WhatsHotFragment();
        break;
    */
    default:
        break;
    }

    /*if (fragment != null) {
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();*/

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    //} else {
        // error in creating fragment
    //  Log.e("MainActivity", "Error in creating fragment");
    //}
    }

    @Override
    public void setTitle(CharSequence title) {
    mTitle = title;
    getSupportActionBar().setTitle(mTitle);
    }

   /**
    * 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.
    mDrawerToggle.syncState();
    }

   @Override
    public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggls
    mDrawerToggle.onConfigurationChanged(newConfig);
    }

    }

这是导航抽屉中的一个项目(第一项,默认情况下必须打开):

package sightsOfAlmaty;

import java.util.Hashtable;


import com.example.new1.GPSTracker;

import com.example.new1.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public class HomeFragment extends sightsOfAlmaty {

public HomeFragment(){}

private GoogleMap map;
GPSTracker gps;

Marker marker;
private Hashtable<String, String> markers;
private ImageLoader imageLoader;
private DisplayImageOptions options;
protected static int position;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mDrawerList.setItemChecked(position, true);
    setTitle(mTitle);
    getLayoutInflater().inflate(R.layout.fragment_home, frameLayout);
    /**
     * Setting title and itemChecked  

    */

    gps = new GPSTracker(this);

    LatLng myloc = new LatLng(gps.getLatitude(), gps.longitude);

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
    map.getUiSettings(  ).setZoomControlsEnabled(true); // true to enable
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(myloc, 15));
     map.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);



}
 }

以下是截图:http://savepic.net/6400885.htmhttp://savepic.net/6399861.htm(如果您不明白我究竟是什么意思)

我在将片段更改为活动后得到了它,所以请帮助我如何解决我的问题。任何建议,答案,评论都表示赞赏!

1 个答案:

答案 0 :(得分:0)

也许有点晚了,但我们走了。这就是您正在使用的#34;导航&#34;当您启动MainActivity时。

    if(isLaunch){
     /**
      *Setting this flag false so that next time it will not open our first activity.
      *We have to use this flag because we are using this BaseActivity as parent activity to our other activity. 
      *In this case this base activity will always be call when any child activity will launch.
      */
    isLaunch = false;
    displayView(0);
}

在我的应用程序中,我使用了这段代码。当您从未运行过您的应用程序时,它没有保存的实例,因此当savedInstanceState为null时,您可以导航到导航程序中所需的索引(因为您的应用程序未在后台运行或处于待机状态)。 MainActivity中的onCreate方法为您提供&#34; savedInstanceState&#34;价值:)

嗯,这是代码:

    if(savedInstanceState == null) {
         displayView(0);
    }

在onCreate中使用它。

这适合你吗?