如何在android中的DrawerLayout中添加Activity类?

时间:2017-01-07 17:25:39

标签: android drawerlayout

我有一些ViewPager的幻灯片显示了应用程序帮助,我也希望在DrawerLayout中显示它。

这是HelpActivity.class:

public class HelpActivity extends Activity {

private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;

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

    // Checking for first time launch - before calling setContentView()
    prefManager = new PrefManager(this);
    if (!prefManager.isFirstTimeLaunch()) {
        launchHomeScreen();
        finish();
    }

    // Making notification bar transparent
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    setContentView(R.layout.fragment_help);

    viewPager = (ViewPager) findViewById(R.id.view_pager);
    dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
    btnSkip = (Button) findViewById(R.id.btn_skip);
    btnNext = (Button) findViewById(R.id.btn_next);


    // layouts of all welcome sliders
    // add few more layouts if you want
    layouts = new int[]{
            R.layout.welcome_1,
            R.layout.welcome_2,
            R.layout.welcome_3,
            R.layout.welcome_4,
            R.layout.welcome_5,
            R.layout.welcome_6,
            R.layout.welcome_7};

    // adding bottom dots
    addBottomDots(0);

    // making notification bar transparent
    changeStatusBarColor();

    myViewPagerAdapter = new MyViewPagerAdapter();
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

    btnSkip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchHomeScreen();
        }
    });

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // checking for last page
            // if last page home screen will be launched
            int current = getItem(+1);
            if (current < layouts.length) {
                // move to next screen
                viewPager.setCurrentItem(current);
            } else {
                launchHomeScreen();
            }
        }
    });
}

private void addBottomDots(int currentPage) {
    dots = new TextView[layouts.length];

    int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
    int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

    dotsLayout.removeAllViews();
    for (int i = 0; i < dots.length; i++) {
        dots[i] = new TextView(this);
        dots[i].setText(Html.fromHtml("&#8226;"));
        dots[i].setTextSize(35);
        dots[i].setTextColor(colorsInactive[currentPage]);
        dotsLayout.addView(dots[i]);
    }

    if (dots.length > 0)
        dots[currentPage].setTextColor(colorsActive[currentPage]);
}

private int getItem(int i) {
    return viewPager.getCurrentItem() + i;
}

private void launchHomeScreen() {
    prefManager.setFirstTimeLaunch(false);
    startActivity(new Intent(HelpActivity.this, MainActivity.class));
    finish();
}

//  viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        addBottomDots(position);

        // changing the next button text 'NEXT' / 'GOT IT'
        if (position == layouts.length - 1) {
            // last page. make button text to GOT IT
            btnNext.setText(/*getString(R.string.start)*/ "Start");
            btnSkip.setVisibility(View.GONE);
        } else {
            // still pages are left
            btnNext.setText(/*getString(R.string.next)*/ "Next");
            btnSkip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
};

/**
 * Making notification bar transparent
 */
private void changeStatusBarColor() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }
}

/**
 * View pager adapter
 */
public class MyViewPagerAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(layouts[position], container, false);
        container.addView(view);

        return view;
    }

    @Override
    public int getCount() {
        return layouts.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }
}

}

这是PrefManager.class

public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;

// shared pref mode
int PRIVATE_MODE = 0;

// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";

private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

public PrefManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setFirstTimeLaunch(boolean isFirstTime) {
    editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
    editor.commit();
}

public boolean isFirstTimeLaunch() {
    return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}

}

我使用此代码将其定义为drawerLayout

  public void selectDrawerItem(MenuItem menuItem) {
         if (menuItem.getItemId()== R.id.nav_item_help) {
        //startActivityForResult(new Intent(this,HelpActivity.class),1000);
        startActivity(new Intent(MainActivity.this,HelpActivity.class));
    }

单击抽屉中的help,没有任何显示。我该怎么办?

这是MainActivity.class:

ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;

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

    FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
    tx.replace(R.id.flContent, new HomeFragment());
    tx.commit();

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //drawer layout
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    actionBarDrawerToggle= setupDrawerToggle();
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //navigation view
    navigationView= (NavigationView) findViewById(R.id.nvView);

    // Setup drawer view
    setupDrawerContent(navigationView);
    actionBarDrawerToggle.syncState();

    // default item of navigation view
   // navigationView.getMenu().getItem(0).setChecked(true);
    navigationView.setCheckedItem(R.id.nav_item_home);


}//onCreate

private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

private void setupDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    return true;
                }
            });
}

public void selectDrawerItem(MenuItem menuItem) {
    if (menuItem.getItemId()==R.id.nav_item_setting){
        startActivityForResult(new Intent(this, SettingActivity.class), 1002);
    }
    if (menuItem.getItemId()== R.id.nav_item_help) {
        //startActivityForResult(new Intent(this,HelpActivity.class),1000);
        startActivity(new Intent(MainActivity.this,HelpActivity.class));
    }

    // Create a new fragment and specify the fragment to show based on nav item clicked
    android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
    Class fragmentClass = null;
    switch(menuItem.getItemId()) {
        case R.id.nav_item_home:
            fragmentClass = HomeFragment.class;
            break;

        case R.id.nav_item_knowledge:
            fragmentClass = HomeFragment.class;
            break;

       /* case R.id.nav_item_help:
            fragmentClass = HelpActivity.class;
            break;*/

        case R.id.nav_item_about:
            fragmentClass =AboutFragment.class;
            break;

        default:
            fragmentClass = HomeFragment.class;
            break;
    } try {
        fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Insert the fragment by replacing any existing fragment
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
    if(currentFragment==null){
        fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
    }else{
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }

    // Highlight the selected item has been done by NavigationView
    menuItem.setChecked(true);


    // Set action bar title
    setTitle(menuItem.getTitle());
    // Close the navigation drawer
    drawerLayout.closeDrawers();
}

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    actionBarDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }  return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);    // `onPostCreate` called when activity start-up is complete after `onStart()`
}

@Override
public void onBackPressed() {
    MainActivity.this.finish();
}

}

1 个答案:

答案 0 :(得分:0)

你的xml中的

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    android:background="@drawable/background_drawer"
    app:headerLayout="@layout/nav_header"
    app:itemIconTint="@color/colorPrimary"
    app:menu="@menu/menu_navigation" />

您必须在menu_navigation

中添加帮助选项
 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_item_help"
            android:icon="@drawable/profile_icon"
            android:title="Help" />

    </group>
</menu>

同样在您的MainActivity中:

    public void selectDrawerItem(MenuItem menuItem) {

    // Create a new fragment and specify the fragment to show based on nav item clicked
    android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
    Class fragmentClass = null;
    switch(menuItem.getItemId()) {

        case R.id.nav_item_setting:
            Intent i = new Intent(MainActivity.this, SettingActivity.class);
            startActivity(i);
            break;
        case R.id.nav_item_help:
            Intent i = new Intent(MainActivity.this, HelpActivity.class);
            startActivity(i);
            break;
        case R.id.nav_item_home:
            fragmentClass = HomeFragment.class;
            break;

        case R.id.nav_item_knowledge:
            fragmentClass = HomeFragment.class;
            break;

       /* case R.id.nav_item_help:
            fragmentClass = HelpActivity.class;
            break;*/

        case R.id.nav_item_about:
            fragmentClass =AboutFragment.class;
            break;

        default:
            fragmentClass = HomeFragment.class;
            break;
    } try {
        fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Insert the fragment by replacing any existing fragment
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
    if(currentFragment==null){
        fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
    }else{
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }

    // Highlight the selected item has been done by NavigationView
    menuItem.setChecked(true);
    // Set action bar title
    setTitle(menuItem.getTitle());
    // Close the navigation drawer
    drawerLayout.closeDrawers();
}

在您的偏好管理员中:

    public void setFirstTimeLaunch(boolean isFirstTime) {
    Editor editor = pref.edit();
    editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
    editor.commit();
   }

startactivitystartActivityForResult之间的区别是:

<强> 1。 startActvity():

startActivity()将启动您要启动的活动,而不必担心startActivity启动的新子活动对父活动的任何结果。

<强> 2。 startAcitvityForResult():

startAcitvityForResult()从activity开始另一个activity,它希望通过startAcitvityForResult()从新启动的子活动中获取一些数据并将其返回到父活动

请参阅此博客:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/