使用标签和片段处理导航项目

时间:2018-07-14 20:53:10

标签: java android android-fragments navbar toolbar

我已经创建了一个导航抽屉,并添加了这样的布局

activity_main

 <?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>

app_bar_main

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            android:layout_gravity="bottom"
            app:tabSelectedTextColor="#fffaf0"/>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

我得到如下所示的结果: enter image description here

但是,我尝试将片段添加到选项卡,以便每个导航项打开一个屏幕,其中包含两个选项卡“ First Semester”和“ Second Semester”,其内容保存在片段xml中,但不起作用。

MainActivity

    package com.lini.bdevelopers.geomaticshandbook;

//import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
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.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.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ViewPager viewPager;
    TabLayout tabLayout;

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

        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();
            }
        });

        viewPager = findViewById(R.id.viewpager);
        //setupViewPager(viewPager);

        tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        DrawerLayout drawer =  findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    // Create adapter for the view  pager
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstSemester(), "First Semester");
        adapter.addFragment(new SecondSemester(), "Second Semester");
        viewPager.setAdapter(adapter);
    }
    private void setupViewPager2(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstSemester2(), "First Semester");
        adapter.addFragment(new SecondSemester2(), "Second Semester");
        viewPager.setAdapter(adapter);
    }
    private void setupViewPager3(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstSemester3(), "First Semester");
        adapter.addFragment(new SecondSemester3(), "Second Semester");
        viewPager.setAdapter(adapter);
    }
    private void setupViewPager4(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstSemeste4r(), "First Semester");
        adapter.addFragment(new SecondSemester4(), "Second Semester");
        viewPager.setAdapter(adapter);
    }
    private void setupViewPager5(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FirstSemester5(), "First Semester");
        adapter.addFragment(new SecondSemester5(), "Second Semester");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {

            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {

            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return mFragmentTitleList.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();

        if (id == R.id.year1) {
            setupViewPager(viewPager);
        } else if (id == R.id.year2) {
            setupViewPager2(viewPager);
        } else if (id == R.id.year3) {
            setupViewPager3(viewPager);
        } else if (id == R.id.year4) {
            setupViewPager4(viewPager);
        } else if (id == R.id.year5) {
            setupViewPager5(viewPager);
        } 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;
    }
}

上面的代码将FirstSemester()和SecondSemester()片段绑定到所有导航项。这可能不是正确的解决方法,因此,我需要建议和帮助,谢谢。

第二 如何将AppBar标题更改为所选导航项的标题?

3 个答案:

答案 0 :(得分:0)

  

第二,如何将AppBar标题更改为   选择了导航项?

在MainActivity类的onNavigationItemSelected()方法中。您可以执行以下操作:

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

    if (id == R.id.year1) {
        getSupportActionBar().setTitle("Year 1");
        setupViewPager(viewPager);
    } else if (id == R.id.year2) {
        getSupportActionBar().setTitle("Year 2");
        setupViewPager2(viewPager);
    } else if (id == R.id.year3) {
        getSupportActionBar().setTitle("Year 3");
        setupViewPager3(viewPager);
    } else if (id == R.id.year4) {
        getSupportActionBar().setTitle("Year 4");
        setupViewPager4(viewPager);
    } else if (id == R.id.year5) {
        getSupportActionBar().setTitle("Year 5");
        setupViewPager5(viewPager);
    } 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;
}

关于您的第一个问题,您正在为导航抽屉中单击的任何项目显示一个viewpager(第一和第二学期),因此您不应期望外观正常。粗略的方法,但是效率不是太差。

我希望这会有所帮助。.编码愉快!

答案 1 :(得分:0)

如果要首先创建YearOne片段并将学期添加到每个Year,则首先需要将YearOne,YearTwo等片段添加到导航抽屉菜单。

我创建了一个简单的应用来说明这一点,https://github.com/mbobiosio/TabLayout

您可以像这样在YearOneFragment中附加TabLayout

mViewPager.setAdapter(new FragmentsAdapter(getChildFragmentManager(), getActivity()));

    mTabLayout.setupWithViewPager(mViewPager);

    mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }
});

答案 2 :(得分:0)

我将分享我在应用程序中使用的内容。您可以重用单个片段。看看这个

Mainactivity.java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener
{
private Toolbar toolbar;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    setTitle(R.string.app_name); //Toolbar title at start.
}

 @Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment;

    if (id == R.id.year1) {
        fragment = new YearFragment(); //Root Fragment then add semester fragment.
        loadFragment(fragment);
        Bundle data = new Bundle();
        data.putString("YEAR","FIRST YEAR"); //Pass year value
        fragment.setArguments(data);
        toolbar.setTitle("FIRST YEAR");
    }
    if (id == R.id.year2) {
        fragment = new YearFragment();//If your view for fragment is different then create new fragment and change here.
        loadFragment(fragment);
        Bundle data = new Bundle();
        data.putString("YEAR","SECOND YEAR"); //Pass year value
        fragment.setArguments(data);
        toolbar.setTitle("SECOND YEAR");
    }
.
.
.
. //Add upto required navigation items.

}

private void loadFragment(Fragment fragment) {
    // load fragment
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, fragment);
    transaction.commit();
}

}

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" />

年份片段

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

public class YearFragment extends Fragment {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout mTabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View rootview = inflater.inflate(R.layout.frag_year,container,false);

    mTabLayout =  rootview.findViewById(R.id.sliding_tabs);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());

    mViewPager =  rootview.findViewById(R.id.vp_container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mTabLayout.setupWithViewPager(mViewPager);

    String year = getArguments().getString("YEAR",""); //Here you can get year value change code according to year value.
}

 public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    String[] titles = {"FIRST SEMESTER"," SECOND SEMESTER"};

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        if(position == 0) {
            return FirstSemester.newInstance(year);
        }
        else {
            return SecondSemester.newInstance(year);
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;
    }
}

}

frag_year.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:id="@+id/sliding_tabs"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_scrollFlags="scroll"
    app:tabIndicatorColor="@color/colorAccent"
    app:tabIndicatorHeight="3dp"
    app:tabMode="fixed"
    app:tabMaxWidth="0dp"
    app:tabGravity="fill"
    app:tabTextColor="@color/textColor" />

<android.support.v4.view.ViewPager
    android:id="@+id/vp_container"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/sliding_tabs" />

FirstSemester.java

public class FirstSemester extends Fragment {

private static String yearValue = "";

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.frag_firstsem,container,false);
    if(yearValue.equals("FIRST YEAR"))
    {
     //Add Code as per your need.
    }
    return rootview;
}

public static FirstSemester newInstance(String Year) {
    FirstSemester fragment = new FirstSemester();
    yearValue = Year;
    return fragment;
}

frag_firstsem.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">

//Add your views for Semster fragment.

</android.support.constraint.ConstraintLayout>

希望这会有所帮助。并且我创建了bundle并通过年份值,仅用于所有导航项目的frament视图是相同的。因此您可以根据年份更改值,否则,如果您的导航项目视图不同,则也应该为Years创建单独的片段并为学期创建单独的片段..