Android:MainActivity/Fragment中的ListView/GridView重叠工具栏

Android:MainActivity/Fragment中的ListView/GridView重叠工具栏,android,listview,android-fragments,android-activity,gridview,Android,Listview,Android Fragments,Android Activity,Gridview,所以我最近一直在学习教程,以便在我的主页中创建一个ListView,它是一个片段。因为这不起作用(据我所知?),我在我的主要活动中实现了以下代码,其中包含一个导航抽屉。我已尝试简化您的理解以及我希望实现以下目标的应用程序顺序: 用户登录应用程序 用户通过Intent 用户可以选择导航抽屉中的各种片段(主页、收藏夹、帮助等) 我还创建了Product类来保存ListView/GridView中图像、标题和描述的方法。我还创建了ListViewAdapter和GridViewAdapter类来扩展L

所以我最近一直在学习教程,以便在我的主页中创建一个
ListView
,它是一个片段。因为这不起作用(据我所知?),我在我的主要活动中实现了以下代码,其中包含一个导航抽屉。我已尝试简化您的理解以及我希望实现以下目标的应用程序顺序:

  • 用户登录应用程序
  • 用户通过
    Intent
  • 用户可以选择导航抽屉中的各种片段(主页、收藏夹、帮助等)
  • 我还创建了Product类来保存ListView/GridView中图像、标题和描述的方法。我还创建了ListViewAdapter和GridViewAdapter类来扩展ListView/GridView中的“产品”

    MainActivity.java:

    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.support.v4.app.FragmentTransaction;
    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 android.view.View;
    import android.view.ViewStub;
    import android.widget.AdapterView;
    import android.widget.GridView;
    import android.widget.ListView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {
    
        private ViewStub stubGrid;
        private ViewStub stubList;
        private ListView listView;
        private GridView gridView;
        private ListViewAdapter listViewAdapter;
        private GridViewAdapter gridViewAdapter;
        private List<Product> productList;
        private int currentViewMode = 0;
    
        static final int VIEW_MODE_LISTVIEW = 0;
        static final int VIEW_MODE_GRIDVIEW = 1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            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);
    
            stubList = (ViewStub) findViewById(R.id.stub_list);
            stubGrid = (ViewStub) findViewById(R.id.stub_grid);
    
            // Inflate ViewStub before we get view
            stubList.inflate();
            stubGrid.inflate();
    
            listView = (ListView) findViewById(R.id.myListView);
            gridView = (GridView) findViewById(R.id.myGridView);
    
            // Get list of products
            getProductList();
    
            // Get current view mode in shared preferences
            SharedPreferences sharedPreferences = getSharedPreferences("View Mode", MODE_PRIVATE);
            currentViewMode = sharedPreferences.getInt("currentViewMode", VIEW_MODE_LISTVIEW); // Default view is ListView
    
            // Register item click
            //listView.setOnItemClickListener(onItemClick);
            //gridView.setOnItemClickListener(onItemClick);
    
            switchView();
        }
    
        private void switchView() {
            if (VIEW_MODE_LISTVIEW == currentViewMode) {
                // Display ListView
                stubList.setVisibility(View.VISIBLE);
                // Hide GridView
                stubGrid.setVisibility(View.GONE);
            } else {
                // Hide ListView
                stubList.setVisibility(View.GONE);
                // Display GridView
                stubGrid.setVisibility(View.VISIBLE);
            }
    
            setAdapters();
    
        }
    
        private void setAdapters() {
            if (VIEW_MODE_LISTVIEW == currentViewMode) {
                listViewAdapter = new ListViewAdapter(this, R.layout.list_item, productList);
                listView.setAdapter(listViewAdapter);
            } else {
                gridViewAdapter = new GridViewAdapter(this, R.layout.grid_item, productList);
                gridView.setAdapter(gridViewAdapter);
            }
        }
    
        @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) {
            switch (item.getItemId()) {
                case R.id.item_menu_1:
                    if (VIEW_MODE_LISTVIEW == currentViewMode) {
                        currentViewMode = VIEW_MODE_GRIDVIEW;
                    } else {
                        currentViewMode = VIEW_MODE_LISTVIEW;
                    }
                    // Switch view
                    switchView();
                    // Save view mode in share preferences
                    SharedPreferences sharePreferences = getSharedPreferences("ViewMode", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharePreferences.edit();
                    editor.putInt("currentViewMode", currentViewMode);
                    editor.commit();
    
                    break;
            }
            // 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.first_fragment) {
                setTitle("Home");
                FirstFragment fragment = new FirstFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment, "fragment1");
                fragmentTransaction.commit();
            } else if (id == R.id.second_fragment) {
                setTitle("Favourites");
                SecondFragment fragment = new SecondFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment, "fragment2");
                fragmentTransaction.commit();
            } else if (id == R.id.third_fragment) {
                setTitle("Account");
                ThirdFragment fragment = new ThirdFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment, "fragment3");
                fragmentTransaction.commit();
            } else if (id == R.id.fourth_fragment) {
                setTitle("Help & Feedback");
                FourthFragment fragment = new FourthFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment, "fragment4");
                fragmentTransaction.commit();
            }
    
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    
        public List<Product> getProductList() {
            // Pseudo code to get product, replace your code to get product here
            productList = new ArrayList<>();
            productList.add(new Product(R.drawable.nightclub, "Title 1", "This is description 1"));
            productList.add(new Product(R.drawable.nightclub, "Title 2", "This is description 2"));
            productList.add(new Product(R.drawable.nightclub, "Title 3", "This is description 3"));
            productList.add(new Product(R.drawable.nightclub, "Title 4", "This is description 4"));
            productList.add(new Product(R.drawable.nightclub, "Title 5", "This is description 5"));
            productList.add(new Product(R.drawable.nightclub, "Title 6", "This is description 6"));
            productList.add(new Product(R.drawable.nightclub, "Title 7", "This is description 7"));
            productList.add(new Product(R.drawable.nightclub, "Title 8", "This is description 8"));
            productList.add(new Product(R.drawable.nightclub, "Title 9", "This is description 9"));
            productList.add(new Product(R.drawable.nightclub, "Title 10", "This is description 10"));
    
            return productList;
        }
    
        /*
        AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Do something when u ser clicks an item
                Toast.makeText(getApplicationContext(), productList.get(position).getTitle() + " - " + productList.get(position).getDescription(), Toast.LENGTH_SHORT).show();
            }
        };*/
    }
    
    导入android.content.SharedReferences;
    导入android.os.Bundle;
    导入android.support.v4.app.FragmentTransaction;
    导入android.support.design.widget.NavigationView;
    导入android.support.v4.view.GravityCompat;
    导入android.support.v4.widget.DrawerLayout;
    导入android.support.v7.app.ActionBarDrawerToggle;
    导入android.support.v7.app.AppActivity;
    导入android.support.v7.widget.Toolbar;
    导入android.view.Menu;
    导入android.view.MenuItem;
    导入android.view.view;
    导入android.view.ViewStub;
    导入android.widget.AdapterView;
    导入android.widget.GridView;
    导入android.widget.ListView;
    导入android.widget.Toast;
    导入java.util.ArrayList;
    导入java.util.List;
    公共类MainActivity扩展了AppCompatActivity
    实现NavigationView.OnNavigationItemSelectedListener{
    私有视图网格;
    私有视图存根列表;
    私有列表视图列表视图;
    私有GridView GridView;
    私有ListViewAdapter ListViewAdapter;
    私有GridViewAdapter GridViewAdapter;
    私有列表产品列表;
    private int currentViewMode=0;
    静态最终整型视图\模式\列表视图=0;
    静态最终int视图\模式\网格视图=1;
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
    设置支持操作栏(工具栏);
    抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
    ActionBarDrawerToggle切换=新建ActionBarDrawerToggle(
    这,抽屉,工具栏,R.string.navigation\u drawer\u open,R.string.navigation\u drawer\u close);
    抽屉。设置抽屉定位器(开关);
    toggle.syncState();
    NavigationView NavigationView=(NavigationView)findViewById(R.id.nav_视图);
    navigationView.setNavigationItemSelectedListener(此);
    存根列表=(视图存根)findViewById(R.id.stub\u列表);
    stubGrid=(ViewStub)findViewById(R.id.stub\u grid);
    //在获得视图之前,将ViewStub充气
    stubList.inflate();
    stubGrid.充气();
    listView=(listView)findViewById(R.id.myListView);
    gridView=(gridView)findViewById(R.id.myGridView);
    //获取产品列表
    getProductList();
    //获取共享首选项中的当前视图模式
    SharedReferences SharedReferences=GetSharedReferences(“查看模式”,模式\私有);
    currentViewMode=SharedReferences.getInt(“currentViewMode”,VIEW\u MODE\u LISTVIEW);//默认视图为LISTVIEW
    //注册项目点击
    //setonitemclick监听器(onItemClick);
    //setonitemclick监听器(onItemClick);
    switchView();
    }
    私有void switchView(){
    如果(视图模式列表视图==当前视图模式){
    //显示列表视图
    setVisibility(View.VISIBLE);
    //隐藏网格视图
    stubGrid.setVisibility(View.GONE);
    }否则{
    //隐藏列表视图
    stubList.setVisibility(View.GONE);
    //显示网格视图
    stubGrid.setVisibility(View.VISIBLE);
    }
    setAdapters();
    }
    私有void setAdapters(){
    如果(视图模式列表视图==当前视图模式){
    listViewAdapter=新listViewAdapter(此,R.layout.list\u项,productList);
    setAdapter(listViewAdapter);
    }否则{
    gridViewAdapter=新的gridViewAdapter(此,R.layout.grid_项,productList);
    setAdapter(gridViewAdapter);
    }
    }
    @凌驾
    public void onBackPressed(){
    抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
    if(抽屉isDrawerOpen(重力压缩机启动)){
    抽屉。关闭抽屉(重力压缩机启动);
    }否则{
    super.onBackPressed();
    }
    }
    @凌驾
    公共布尔onCreateOptions菜单(菜单){
    //为菜单充气;这会将项目添加到操作栏(如果存在)。
    getMenuInflater().充气(R.menu.main,menu);
    返回true;
    }
    @凌驾
    公共布尔值onOptionsItemSelected(菜单项项){
    开关(item.getItemId()){
    案例R.id.项目\菜单\ 1:
    如果(视图模式列表视图==当前视图模式){
    currentViewMode=视图\模式\网格视图;
    }否则{
    currentViewMode=视图\模式\列表视图;
    }
    //切换视图
    switchView();
    //在共享首选项中保存视图模式
    SharedReferences sharePreferences=GetSharedReferences(“查看模式”,模式\私有);
    SharedReferences.Editor=sharePreferences.edit();
    编辑器.putInt(“currentViewMode”,currentViewMode);
    commit();
    打破
    }
    //处理操作栏项目单击此处。操作栏将
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.example.michael.whatsupldn.MainActivity"
        tools:showIn="@layout/app_bar_main">
    
        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:alpha="200"/>
    </LinearLayout>
    
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayoutx mlns: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"/>
    
        <ViewStub
            android:id="@+id/stub_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:inflatedId="@+id/showlayout"
            android:layout="@layout/my_listview"/>
    
        <ViewStub
            android:id="@+id/stub_grid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:inflatedId="@+id/showlayout"
            android:layout="@layout/my_gridview"/>
    
    </android.support.v4.widget.DrawerLayout>
    
    <?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="com.example.michael.whatsupldn.MainActivity">
    
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/london_skyline_dark"
            android:layout_alignParentTop="true"
            android:id="@+id/imageView"
            android:contentDescription="@string/london_skyline"/>
    
        <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.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
    </android.support.design.widget.CoordinatorLayout>
    
    // activity_Main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayoutx mlns: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>
    
    // first_fragment.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false" />
    
    </RelativeLayout>
    
    //FirstFragment.java
    
    .........
    ...............
    
    RecyclerView mRecyclerView;
    
    RecyclerView.LayoutManager mGridLayoutManager;
    RecyclerView.LayoutManager mLinearLayoutManager;
    
    boolean isList = false; // By default list will be shown
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
    
        // Required for option menu
        setHasOptionsMenu(true);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.first_fragment, null);
    
        //REFERENCE
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
    
        // Layout manager
        mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    
        // Set layout manager
        toggleListGrid();
    
    
        // Set adapter to RecyclerView
        ...............
        ....................
    
        return rootView;
    }
    
    public void toggleListGrid() {
    
        isList = !isList;
    
        if(isList)
            mRecyclerView.setLayoutManager(mLinearLayoutManager);
        else
            mRecyclerView.setLayoutManager(mGridLayoutManager);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.main, menu);
    
        super.onCreateOptionsMenu(menu, inflater);
    }   
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.item_menu_1:
            {
                // Change view
                toggleListGrid();
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);       
        }
    }
    
    .........
    ...................