每当我尝试从 Fragment java 文件中更改片段的某些属性时,应用程序就会崩溃
App crashes whenever I try to change some attribute of a fragment from inside the Fragment java file
所以基本上我面临的问题是,每当我尝试为某些视图分配 .settext()
等值时,我的应用程序就会崩溃。
基本上,我从 Main activity 创建了一个导航抽屉。在导航抽屉中,我有两个菜单选项,单击每个选项都会打开一个片段。此外,由于第一个片段也是主屏幕,因此每当我打开 Main activity.
时,我都会启动第一个片段
现在,第二个片段是我面临的问题。我有一个带有一些视图的片段布局以及一个片段 java 文件。每当我尝试从 java 文件中为这些视图分配一些值时,应用程序就会崩溃。我已经粘贴了我的片段 xml 文件和 java 文件的代码以及下面的错误。
<?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:orientation="vertical"
tools:context=".ProfileFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/up"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.4">
<com.scwang.wave.MultiWaveHeader
app:mwhVelocity="2"
app:mwhStartColor="@color/colorAccent"
app:mwhCloseColor="@color/colorPrimaryDark"
app:mwhGradientAngle="-90"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/waveview"
/>
<TextView
android:id="@+id/name_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="User"
android:textColor="#ffff"
android:textSize="25sp" />
</RelativeLayout>
</LinearLayout>
</FrameLayout>
我的 java 文件是:
public class ProfileFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
final TextView profile_name = getActivity().findViewById(R.id.name_display);
profile_name.setText("Hi");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
我得到的错误是:
2021-01-27 15:31:22.641 29226-29226/com.appname.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appname.app, PID: 29226
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.appname.app.ProfileFragment.onCreate(ProfileFragment.java:71)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7542)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
所以我猜错误大概在:
profile_name.setText("Hi");
为简单起见,我删除了不必要的代码。
您在此处定义了代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
final TextView profile_name = getActivity().findViewById(R.id.name_display);
profile_name.setText("Hi");
}
但这不是用于片段的正确生命周期方法,相反,您应该覆盖并使用 onViewCreated:
@Override
public void onViewCreated(@NotNull View view, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// your code here
}
更多信息 ,但具体来说:
The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
所以此时,还没有视图,这就是您的代码崩溃的原因
所以基本上我面临的问题是,每当我尝试为某些视图分配 .settext()
等值时,我的应用程序就会崩溃。
基本上,我从 Main activity 创建了一个导航抽屉。在导航抽屉中,我有两个菜单选项,单击每个选项都会打开一个片段。此外,由于第一个片段也是主屏幕,因此每当我打开 Main activity.
时,我都会启动第一个片段现在,第二个片段是我面临的问题。我有一个带有一些视图的片段布局以及一个片段 java 文件。每当我尝试从 java 文件中为这些视图分配一些值时,应用程序就会崩溃。我已经粘贴了我的片段 xml 文件和 java 文件的代码以及下面的错误。
<?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:orientation="vertical"
tools:context=".ProfileFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/up"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.4">
<com.scwang.wave.MultiWaveHeader
app:mwhVelocity="2"
app:mwhStartColor="@color/colorAccent"
app:mwhCloseColor="@color/colorPrimaryDark"
app:mwhGradientAngle="-90"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/waveview"
/>
<TextView
android:id="@+id/name_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:text="User"
android:textColor="#ffff"
android:textSize="25sp" />
</RelativeLayout>
</LinearLayout>
</FrameLayout>
我的 java 文件是:
public class ProfileFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
final TextView profile_name = getActivity().findViewById(R.id.name_display);
profile_name.setText("Hi");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
}
我得到的错误是:
2021-01-27 15:31:22.641 29226-29226/com.appname.app E/AndroidRuntime: FATAL EXCEPTION: main Process: com.appname.app, PID: 29226 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.appname.app.ProfileFragment.onCreate(ProfileFragment.java:71) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838) at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197) at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080) at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) at androidx.fragment.app.FragmentManagerImpl.run(FragmentManagerImpl.java:150) at android.os.Handler.handleCallback(Handler.java:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:221) at android.app.ActivityThread.main(ActivityThread.java:7542) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
所以我猜错误大概在:
profile_name.setText("Hi");
为简单起见,我删除了不必要的代码。
您在此处定义了代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
final TextView profile_name = getActivity().findViewById(R.id.name_display);
profile_name.setText("Hi");
}
但这不是用于片段的正确生命周期方法,相反,您应该覆盖并使用 onViewCreated:
@Override
public void onViewCreated(@NotNull View view, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// your code here
}
更多信息
The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
所以此时,还没有视图,这就是您的代码崩溃的原因