【问题标题】:Replace fragments in default Android Studio navigation drawer替换默认 Android Studio 导航抽屉中的片段
【发布时间】:2020-05-16 15:38:28
【问题描述】:

我正在尝试在 Android Studio 的默认导航抽屉中用图库片段替换主页片段,反之亦然。这是主类:

package com.example.navdrawer;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @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 onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

这是家庭片段类:

import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.navdrawer.R;
import com.example.navdrawer.ui.gallery.GalleryFragment;

public class HomeFragment extends Fragment {
    Button button;
    TextView textView = null;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        textView = root.findViewById(R.id.text_home);
        textView.setText("This is home fragment");
        button = root.findViewById(R.id.home_button);
        return root;
    }
    public void onClick(View v) {
//respond to clicks
        if (v.getId() == R.id.home_button) {
            GalleryFragment frag = new GalleryFragment();
            FragmentManager ft = getFragmentManager();
            FragmentTransaction fragmentTransaction =ft.beginTransaction();
            fragmentTransaction.replace(R.id.home, frag);
            // ft.addToBackStack(null);
            fragmentTransaction.commit();
        }

        }

}

图库片段与主页片段相似:

 package com.example.navdrawer.ui.gallery;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.navdrawer.R;
import com.example.navdrawer.ui.home.HomeFragment;

public class GalleryFragment extends Fragment {
    Button button;
    TextView textView = null;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_gallery, container, false);
        textView = root.findViewById(R.id.text_gallery);
        textView.setText("This is gallery fragment");
        button = root.findViewById(R.id.gallery_button);
        return root;
    }

    public void onClick(View v) {
//respond to clicks
        if (v.getId() == R.id.gallery_button) {
            HomeFragment frag = new HomeFragment();
            FragmentManager ft = getFragmentManager();
            FragmentTransaction fragmentTransaction =ft.beginTransaction();
            fragmentTransaction.replace(R.id.gallery, frag);
            // ft.addToBackStack(null);
            fragmentTransaction.commit();
        }

    }

}

我已经为 home 片段获取了这个 xml,它与画廊片段中的 xml 类似:

 <?xml version="1.0" encoding="utf-8"?>
<ScrollView 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/scrollView2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <RelativeLayout
        android:id="@+id/home"
        android:screenOrientation="portrait"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_home"
                android:layout_marginTop="50dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

        <Button
            android:id="@+id/home_button"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/text_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/replace1" />


    </RelativeLayout>
</ScrollView>

我不知道为什么它不起作用。

【问题讨论】:

    标签: java android replace navigation fragment


    【解决方案1】:

    默认模板使用Navigation component,这意味着您无需手动执行 FragmentTransactions。相反,根据the documentation,您可以将GalleryFragment 添加到导航XML 文件(在res/navigation 下),然后调用navigate() 前往该目的地,替换您当前所在的屏幕。

    【讨论】:

    • 谢谢。在导航文件夹中,我有 mobile_navigation.xml,我相信它用于在片段之间导航,因为所有片段都在那里。我尝试将此行用于按钮,但它不起作用“NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment); navController.navigate(R.id.nav_gallery);”
    • 你说什么“它不工作”?您能用收到的错误消息更新您的问题吗?
    • 当我按下那个按钮时什么也没发生,我已经找到了解决方案。我已经在下面回答了我的帖子,但我也想知道如何在不使用按钮和“onclicklistener”的情况下导航到另一个片段,也许使用函数或其他类型的“动作监听”。
    【解决方案2】:

    我从这篇文章中找到了答案:link 对于片段之间的导航,我所要做的就是在“onCreateView”函数中实现这个方法:

    button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.nav_gallery, null));
    

    另一种方法是:

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Navigation.findNavController(view).navigate(R.id.nav_gallery);
                }
            });
    

    我仍然不知道如何在函数内部使用条件“if, else”语句在片段之间导航,也许这将暗示另一种类型的“动作监听”...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多