如何通过导航抽屉在主活动中显示片段?

时间:2019-02-17 04:08:09

标签: java android android-fragments android-recyclerview navigation-drawer

我想通过单击导航抽屉中的相应选项来显示三个片段。我的导航抽屉显示和打开/关闭都很好。但是我无法在“活动”中显示任何片段。每当我单击一个选项时,主屏幕便保持空白。没有编译错误。我是Android开发和Java开发人员的新手,并且我一直在努力完成一个月的项目,因此一旦我可以开始工作,它将立即完成。您可能会看到一些冗余代码实例,因为我只是想尝试所有可行的方法,而且不确定要删除什么,因此对此做任何澄清也将有所帮助。

片段应作为结果显示在RecyclerView中。

MainActivity:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nView;

private ActionBarDrawerToggle toggle;

private RequestQueue queue;

private List<ATM> atmList;

private RecyclerView atmView;

private AtmRecyclerViewAdapter atmRecyclerViewAdapter;



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

    // Set a Toolbar to replace the ActionBar.
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Find drawer layout
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Find drawer view
    nView = (NavigationView) findViewById(R.id.nav_view);
    // Set up drawer view
    setupDrawerContent(nView);

    // Not sure what this does
    nView.setNavigationItemSelectedListener(this);

    toggle = new ActionBarDrawerToggle(
            this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);

    // Tie DrawerLayout events to the ActionBarDrawerToggle
    mDrawer.addDrawerListener(toggle);


    queue = Volley.newRequestQueue(this);



    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);

        // Pass any configuration change to the drawer toggles
        toggle.onConfigurationChanged(newConfig);

    }

    @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.

        // The action bar home/up action should open or close the drawer.

        switch (item.getItemId()) {

            case android.R.id.home:

                mDrawer.openDrawer(GravityCompat.START);

                return true;

        }

        if (toggle.onOptionsItemSelected(item)) {

            return true;

        }

/*        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.nav_items_catalog) {
            // Handle the items catalog action
        } else if (id == R.id.nav_items_search) {

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

/*
            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {

                            try {

                                for (int i = 0; i < response.length(); i++) {

                                    JSONObject atmObj = response.getJSONObject(i);

                                    ATM atm = new ATM();

                                    atm.setAtmId(atmObj.getString("atmid"));
                                    atm.setTitle(atmObj.getString("title"));
                                    atm.setAddress(atmObj.getString("address"));
                                    atm.setType(atmObj.getString("type"));
                                    atm.setLat(atmObj.getDouble("lat"));
                                    atm.setLon(atmObj.getDouble("lon"));
                                    atm.setOnlineStatus(atmObj.getString("onlineStatus"));

                                    atmList.add(atm);

                                    // Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());

                                }

//                                atmView = findViewById(R.id.atmRecyclerView);
//                                atmView.setHasFixedSize(true);
//                                atmView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                                atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
                                        (MainActivity.this, atmList);
                                atmView.setAdapter(atmRecyclerViewAdapter);
                                atmRecyclerViewAdapter.notifyDataSetChanged();

                            } catch (JSONException e) {

                                e.printStackTrace();

                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    error.printStackTrace();

                }
            });

            queue.add(jsonArrayRequest);
*/

        }

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

    private void setupDrawerContent(NavigationView navigationView) {

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

    }

    public void selectDrawerItem(MenuItem menuItem) {

        // Create a new fragment and specify the fragment to show based on nav item clicked

        Fragment fragment = null;

        Class fragmentClass;

        switch(menuItem.getItemId()) {

            case R.id.nav_items_catalog:

                fragmentClass = ShowItems.class;

                // TODO: Find out how to show the fragments in these calls

//                fragment.listItems(???);

                break;

            case R.id.nav_items_search:

                fragmentClass = SearchItems.class;

                break;

            case R.id.nav_atms:

                fragmentClass = ShowATMs.class;

/*
                atmView = findViewById(R.id.atmRecyclerView);
                atmView.setHasFixedSize(true);
                atmView.setLayoutManager(new LinearLayoutManager(this));
*/

                break;

            default:

                fragmentClass = ShowItems.class;

        }

        try {

            fragment = (Fragment) fragmentClass.newInstance();

        } catch (Exception e) {

            e.printStackTrace();

        }

        // Insert the fragment by replacing any existing fragment

        FragmentManager fragmentManager = getSupportFragmentManager();

        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

        mDrawer.closeDrawers();

    }

}

ShowATMs方法-想要以RecyclerView格式显示ATM对象的列表:

public class ShowATMs extends Fragment {

    private RecyclerView atmView;

    private AtmRecyclerViewAdapter atmRecyclerViewAdapter;

    private RequestQueue queue;

    // TODO: NEED TO CREATE A VIEW THAT WILL INFLATE CORRECT LAYOUT HERE

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

        // Is this line needed?
        super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.atm_view, container, false);
        atmView = rootView.findViewById(R.id.atmRecyclerView);
        atmView.setHasFixedSize(true);
        atmView.setLayoutManager(new LinearLayoutManager(getContext()));

        final List<ATM> atmList = new ArrayList<>();

        queue = Volley.newRequestQueue(getContext());

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        try {

                            for (int i = 0; i < response.length(); i++) {

                                JSONObject atmObj = response.getJSONObject(i);

                                ATM atm = new ATM();

                                atm.setAtmId(atmObj.getString("atmid"));
                                atm.setTitle(atmObj.getString("title"));
                                atm.setAddress(atmObj.getString("address"));
                                atm.setType(atmObj.getString("type"));
                                atm.setLat(atmObj.getDouble("lat"));
                                atm.setLon(atmObj.getDouble("lon"));
                                atm.setOnlineStatus(atmObj.getString("onlineStatus"));

                                atmList.add(atm);

                                // Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());

                            }

                        atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
                                (getContext(), atmList);
                        atmView.setAdapter(atmRecyclerViewAdapter);
                        atmRecyclerViewAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {

                            e.printStackTrace();

                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                error.printStackTrace();

            }
        });

        queue.add(jsonArrayRequest);

        return rootView;

    }

}

XML文件

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

    <!-- This LinearLayout represents the contents of the screen  -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <fragment android:name="com.camelr.bilal.camelrecommerceproject.Fragments.ShowATMs"
            android:id="@+id/ATMs"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            tools:layout="@layout/atm_view" />

        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <!--<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"
        android:background="@color/colorPrimary"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/drawer_view" />

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

atm_view.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!--
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">
-->

    <android.support.v7.widget.RecyclerView
        android:id="@+id/atmRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

我还有另外两个片段,我将它们设置得有些不同,但是只显示了一个用于ATM的片段,因为我觉得它最接近工作。我感谢您的宝贵时间,并帮助这里的任何经验丰富的程序员都可以给我。如果我需要提供更多信息以帮助解决我的情况,请告诉我。谢谢

0 个答案:

没有答案