2016-03-12 5 views
0

Я создал ящик для навигации, и теперь я хочу использовать его во всей своей деятельности, может ли кто-нибудь сказать мне, как это делается? я прошел через разных ансеров, но это не помогло, я создал навигационный ящик, и теперь я хочу использовать его во всей своей деятельности, может ли кто-нибудь сказать мне, как это делается? Я прошел через различные ansers, но это не помоглокак использовать навигационный ящик во всех видах деятельности моего проекта

вот мой код:

public class AbstractActivity extends AppCompatActivity { 
    private String[] mPlanetTitles; 
    private LinearLayout mDrawerList; 
    protected DrawerLayout mDrawerLayout; 
    protected ActionBarDrawerToggle mDrawerToggle; 
    private CharSequence mDrawerTitle; 
    private CharSequence mTitle; 
    protected Toolbar toolbar; 
    protected FrameLayout framelayout; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_abstract); 
     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

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

     mPlanetTitles = getResources().getStringArray(R.array.planets_array); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (LinearLayout) findViewById(R.id.left_drawer); 
     framelayout = (FrameLayout)findViewById(R.id.content_frame); 


     mTitle = mDrawerTitle = getTitle().toString(); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 
       toolbar, R.string.drawer_open, R.string.drawer_close){ 

      public void onDrawerClosed(View view) { 
       super.onDrawerClosed(view); 
       getSupportActionBar().setTitle(mTitle); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 

      /** Called when a drawer has settled in a completely open state. */ 
      public void onDrawerOpened(View drawerView) { 
       super.onDrawerOpened(drawerView); 
       getSupportActionBar().setTitle(mDrawerTitle); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 


     }; 



     mDrawerLayout.setDrawerListener(mDrawerToggle); 


    } 

    protected void onPostCreate(Bundle savedInstanceState) { 
     super.onPostCreate(savedInstanceState); 
     // Sync the toggle state after onRestoreInstanceState has occurred. 
     mDrawerToggle.syncState(); 
    } 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     mDrawerToggle.onConfigurationChanged(newConfig); 
    } 

    public void setTitle(CharSequence title) { 

     mTitle = title; 
     getSupportActionBar().setTitle(mTitle); 
    } 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     // If the nav drawer is open, hide action items related to the content view 
     boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
     menu.findItem(R.id.action_Aboutus).setVisible(!drawerOpen); 
     return super.onPrepareOptionsMenu(menu); 
    } 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu, menu); 
     return true; 


    } 

    private void selectItem(int position) { 
     switch(position) { 
      case 1: 
       Intent a = new Intent(this, Welcome.class); 
       startActivity(a); 
       break; 
      case 2: 
       Intent b = new Intent(this, Welcome.class); 
       startActivity(b); 
       break; 
      default: 
     } 
    } 

    public boolean onOptionsItemSelected(MenuItem item){ 
     int items = item.getItemId(); 
     switch(items){ 

      case R.id.action_Settings:{ 
       Intent intent = new Intent(this,Settings.class); 
       startActivity(intent); 

      }break; 

      case R.id.action_Contact_us:{ 
       Intent intent = new Intent(this,Contact.class); 
       startActivity(intent); 

      }break; 

      case R.id.action_Aboutus:{ 
       Intent intent = new Intent(this,ChartStyle.class); 
       startActivity(intent); 

      }break; 

      case R.id.action_Profile:{ 
       Intent intent = new Intent(this,ChartStyle.class); 
       startActivity(intent); 

      }break; 
     } 

     return super.onOptionsItemSelected(item); 
    } 


} 

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <include layout="@layout/toolbar"/> 
    <!-- The main content view --> 
    <FrameLayout 
     android:id="@+id/content_frame" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <!-- The navigation drawer --> 
    <LinearLayout android:id="@+id/left_drawer" 
     android:layout_width="280dp" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:orientation="vertical" 
     android:choiceMode="singleChoice" 
     android:divider="@android:color/transparent" 
     android:dividerHeight="0dp" 

     android:background="#0F6177"> 
     <LinearLayout android:id="@+id/view" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:orientation="vertical"> 

      <include layout="@layout/navigation_drawer"></include> 
     </LinearLayout> 

    </LinearLayout> 


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

Я думаю, одна панель навигации может быть использована только на активности. вы можете добавить несколько фрагментов в свою деятельность. таким образом ваш навигационный ящик будет показан со всеми фрагментами. –

ответ

0

Итак, в первую очередь вы должны создать базовый абстрактный Activity с DrawerLayout:

public abstract class NavigationActivity extends AppCompatActivity { 

    private DrawerLayout mDrawerLayout; 
    private ActionBarDrawerToggle mDrawerToggle; 

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

     if (getSupportActionBar() != null) { 
      getSupportActionBar().setDisplayShowHomeEnabled(true); 
      getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
      getSupportActionBar().setDisplayShowTitleEnabled(true); 
      getSupportActionBar().setTitle("Title"); 
     } 
    } 

    /** 
    * This method overrides the setContentView method to set DrawerLayout as a main layout. 
    * 
    * @param layoutResID Layout, which will be set in DrawerLayout as a content frame 
    */ 
    @Override 
    public void setContentView(final int layoutResID) { 
     super.setContentView(R.layout.navigation_drawer); 

     final ViewStub content = (ViewStub) findViewById(R.id.content_frame); 
     content.setLayoutResource(layoutResID); 
     content.inflate(); 

     initDrawer(); 
    } 

    /** 
    * This method initializes DrawerLayout and DrawerToggle 
    */ 
    private void initDrawer() { 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); 

     mDrawerToggle = new ActionBarDrawerToggle(
       this, 
       mDrawerLayout, 
       null, 
       R.string.drawer_open, 
       R.string.drawer_close 
     ) { 
      public void onDrawerClosed(final View view) { 
       //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 

      public void onDrawerOpened(final View drawerView) { 
       //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 
     }; 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 
    } 

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

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

    @Override 
    public boolean onOptionsItemSelected(final MenuItem item) { 
     return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); 
    } 

    /** 
    * This method is called when user presses the back button. If the drawer is opened, it will be closed. 
    * Otherwise will be called the parent implementation. 
    */ 
    @Override 
    public void onBackPressed() { 
     if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { 
      mDrawerLayout.closeDrawers(); 
     } else { 
      super.onBackPressed(); 
     } 
    } 
} 

который использует макет navigation_drawer.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_width="match_parent" 
    android:layout_height="match_parent"> 

    <ViewStub 
     android:id="@+id/content_frame" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <RelativeLayout 
     android:id="@+id/drawer_container" 
     android:layout_width="@dimen/drawer_width" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:clickable="true" 
     android:background="@color/gray_dark" 
     android:layout_gravity="start"> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="This is drawer"/> 

    </RelativeLayout> 

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

После что вы можете просто создать Activity и установить его макет в ViewStub с идентификатором «content_frame». Это будет сделано автоматически setContentView методом в NavigationActivity

public class MainActivity extends NavigationActivity { 

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

Вы также должны использовать тему с ActionBar:

<resources 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 

    <!-- Base application theme. --> 
    <style name="AppTheme" parent="Theme.AppCompat.Light"> 
     <item name="actionBarStyle">@style/MyActionBar</item> 
    </style> 

    <style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid"> 
     <item name="background">@android:color/white</item> 
     <item name="android:background" tools:ignore="NewApi">@android:color/white</item> 
    </style> 

</resources> 

И установить его в файле manifest:

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

. ..

+0

как установить макет в viewstub с id contentframe – bipin

+0

Это будет сделано автоматически в методе setContentView в NavigationActivity. Так что просто позвоните в setContentView (..), как обычно, – yital9

+0

не могу сделать это в этом же классе? – bipin

0

Я включил этот код но оно не работает

package com.astro.famouspandit.Activities.Abstract; 
import android.content.res.Configuration; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v4.view.GravityCompat; 
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.MenuItem; 
import android.view.View; 
import android.view.ViewStub; 

import com.astro.famouspandit.R; 

public abstract class NavigationActivity extends AppCompatActivity { 

    private DrawerLayout mDrawerLayout; 
    private ActionBarDrawerToggle mDrawerToggle; 

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

     if (getSupportActionBar() != null) { 
      getSupportActionBar().setDisplayShowHomeEnabled(true); 
      getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
      getSupportActionBar().setDisplayShowTitleEnabled(true); 
      getSupportActionBar().setTitle("Title"); 
     } 
    } 

    /** 
    * This method overrides the setContentView method to set DrawerLayout as a main layout. 
    * 
    * @param layoutResID Layout, which will be set in DrawerLayout as a content frame 
    */ 
    @Override 
    public void setContentView(final int layoutResID) { 
     super.setContentView(R.layout.activity_navigation); 

     final ViewStub content =(ViewStub)findViewById(R.id.content_frame); 
     content.setLayoutResource(layoutResID); 
     content.inflate(); 

     initDrawer(); 
    } 

    /** 
    * This method initializes DrawerLayout and DrawerToggle 
    */ 
    private void initDrawer() { 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerLayout.setDrawerShadow(R.drawable.ic_drawer_button, GravityCompat.START); 

     mDrawerToggle = new ActionBarDrawerToggle(
       this, 
       mDrawerLayout, 
       null, 
       R.string.drawer_open, 
       R.string.drawer_close 
     ) { 
      public void onDrawerClosed(final View view) { 
       //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 

      public void onDrawerOpened(final View drawerView) { 
       //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
      } 
     }; 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 
    } 

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

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

    @Override 
    public boolean onOptionsItemSelected(final MenuItem item) { 
     return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); 
    } 

    /** 
    * This method is called when user presses the back button. If the drawer is opened, it will be closed. 
    * Otherwise will be called the parent implementation. 
    */ 
    @Override 
    public void onBackPressed() { 
     if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { 
      mDrawerLayout.closeDrawers(); 
     } else { 
      super.onBackPressed(); 
     } 
    } 
} 

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

    <ViewStub 
     android:id="@+id/content_frame" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <RelativeLayout 
     android:id="@+id/drawer_container" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:clickable="true" 
     android:background="@android:color/white" 
     android:layout_gravity="start"> 


    </RelativeLayout> 

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

в этом классе я простирающийся его:

public class Contact extends NavigationActivity implements View.OnClickListener { 
    private EditText mName,mNumber,mEmail,mMessage; 
    private FancyButton mSbmt; 

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