带有TabView

时间:2016-09-29 21:44:51

标签: android android-fragments fragment

我偶然发现了一个疯狂的小'虫',或者我只是做错了什么。我试图在主要活动中获取滑动选项卡视图,滑动tabView完美工作但主要问题是当单击导航抽屉菜单然后片段相互重叠。请帮助..

这是我的两个tabView片段

1.NewsFragment

public class NewsFragment extends Fragment {

public static NewsFragment newInstance(){
    NewsFragment newsFragment=new NewsFragment();
    return newsFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.news_fragment,null);
}}

2.NoticeFragment

public class NoticeFragment extends Fragment {
public static NoticeFragment newInstance(){
    NoticeFragment noticeFragment=new NoticeFragment();
    return noticeFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.notice_fragment, container, false);
}}

这是我的两个xml for two fragment

1.News_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="120dp"
    android:textSize="30sp"
    android:gravity="center"
    android:id="@+id/textView"
    android:layout_centerHorizontal="true"
    android:textColor="@android:color/holo_blue_dark"
    android:text="News\nFragment"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:textSize="15sp"
    android:layout_marginTop="10dp"
    android:layout_centerHorizontal="true"
    android:text="Android Sikkha"
    android:textColor="#000"
    android:layout_below="@+id/textView"
    android:textStyle="italic"/>
 </RelativeLayout>

2.notice_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="120dp"
    android:textSize="30sp"
    android:gravity="center"
    android:id="@+id/textView"
    android:layout_centerHorizontal="true"
    android:textColor="@android:color/holo_blue_dark"
    android:text="Notice\nFragment"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:textSize="15sp"
    android:layout_marginTop="10dp"
    android:layout_centerHorizontal="true"
    android:text="Android Sikkha"
    android:textColor="#000"
    android:layout_below="@+id/textView"
    android:textStyle="italic"/>

</RelativeLayout>

我有另一个名为Home的java文件,它与前一个java文件相同,xml也是一样。

这是MainActivity

package com.example.user.navwithtab;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
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.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
 DrawerLayout drawer;
 ViewPager mViewPager;


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

    // Setear adaptador al viewpager.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    setupViewPager(mViewPager);

    // Preparar las pestañas
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
    tabs.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    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);
}
private void setupViewPager(ViewPager viewPager) {
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(NewsFragment.newInstance(), "News");
    adapter.addFragment(NoticeFragment.newInstance(), "Notice");
    viewPager.setAdapter(adapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}





@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.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();

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

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    android.app.FragmentManager fragmentManager=getFragmentManager();

    if (id == R.id.home) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
    } else if (id == R.id.announcement) {
        fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).commit();

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

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

    } else if (id == R.id.nav_send) {

    }

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

这里是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
 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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

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

很抱歉很长的帖子。

注意:导航抽屉和滑动视图工作正常,但问题出在片段叠加上。after clicking navigationbarmenu

这是我的logcat

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.user.navwithtab, PID: 3400
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.closeDrawer(int)' on a null object reference
                  at com.example.user.navwithtab.MainActivity.onNavigationItemSelected(MainActivity.java:157)
                  at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:153)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
                  at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:328)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at     android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:0)

onNavigationItemSelected方法中,请勿再次创建DrawerLayout。只需致电closeDrawer

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); --> remove this line of code
drawer.closeDrawer(GravityCompat.START);

<强>更新

在onCreate方法中更改此行代码

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

并添加此行代码

DrawerLayout drawer

在这行代码下面

 ViewPager mViewPager;

并删除onNavigationItemSelected方法

中指定的代码行

答案 1 :(得分:0)

if (id == R.id.home) {
    fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
} else if (id == R.id.announcement) {
    fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).commit();

更新上面的代码如下:

if (id == R.id.home) {
fragmentManager.beginTransaction().replace(R.id.content_frame,new HomeFragment()).addToBackStack(null).commit();
} else if (id == R.id.announcement) {
fragmentManager.beginTransaction().replace(R.id.content_frame,new AnnouncementFragment()).addToBackStack(null).commit();