首页 > 解决方案 > 新实例();在片段中收到 null

问题描述

再会。

在将可变数据从 Activity 发送到 Fragment 时,我遇到了问题。

这是我的代码

活动.java

    if (savedInstanceState == null) {
        Fragment_Voter_Home fragment = Fragment_Voter_Home.newInstance(Pstud_no);
        getSupportFragmentManager().beginTransaction().replace(R.id.voter_fragment,
                new Fragment_Voter_Home()).commit();
        navigationView.setCheckedItem(R.id.voter_home);
    }

然后在

片段.java

公共类 Fragment_Voter_Home 扩展 Fragment {

private static final String ARG_STUDNO = "stud_no";

private String student_no;

public static Fragment_Voter_Home newInstance(String student_no) {

    Fragment_Voter_Home fragment = new Fragment_Voter_Home();
    Bundle args = new Bundle();
    args.putString(ARG_STUDNO, student_no);
    fragment.setArguments(args);
    return fragment;
}

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


    View v = inflater.inflate(R.layout.fragment_voter_home, container, false);
    TextView textView = v.findViewById(R.id.voter_fragment_textview);

    if (getArguments() != null) {
        student_no = getArguments().getString(ARG_STUDNO);
    }

    textView.setText("Welcome, "+student_no);

    return v;

}
}

这是我的 Fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:background="@android:color/white">

<TextView
    android:id="@+id/voter_fragment_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:gravity="center_vertical|center_horizontal|center"
    android:text="Home"
    android:textSize="30sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
    </FrameLayout>

然后运行这就是我得到的,

“欢迎,空”

我已经尝试过这个线程中的解决方案Send a string value from Activity to Fragment in Android但它们都不起作用。

我是android开发的新手。谢谢你。

标签: androidandroid-fragments

解决方案


因为您的代码不正确,请将您的代码更改为

Fragment_Voter_Home fragment = Fragment_Voter_Home.newInstance(Pstud_no);
getSupportFragmentManager().beginTransaction().replace(R.id.voter_fragment,
                fragment).commit();

代替

Fragment_Voter_Home fragment = Fragment_Voter_Home.newInstance(Pstud_no);
getSupportFragmentManager().beginTransaction().replace(R.id.voter_fragment,
                new Fragment_Voter_Home()).commit();

推荐阅读