[英]Why am I getting a null value when trying to access a fragment view from the parent activity?
First , I know that there are a lot of similar questions asked about that before , but none of them answers my question . 首先,我知道以前有很多类似的问题要问,但是没有一个回答我的问题。
I'll keep it simple . 我会保持简单。
I have a class called MainActivity
which includes the following code : 我有一个名为
MainActivity
的类,其中包括以下代码:
public class MainActivity extends AppCompatActivity {
Car myCar = new Car();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.buttonsContainer,myCar,"me").commitNow();
View v = myCar.getView(); // returns null
Button b = v.findViewById(R.id.submitButton); //throws an exception as I'm trying to execute the "findViewById" method on a null object , as the debugger say .
b.setText("It works !"); // it doesn't
}
}
and I have a fragment
that includes a single button with the following code : 并且我有一个
fragment
,其中包含带有以下代码的单个按钮:
public class Car extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.car, container, false);
return rootView;
}
}
It does nothing but showing the layout that corresponds to it. 除了显示与之对应的布局外,它什么也不做。
Here's my MainActivity
XML
file : 这是我的
MainActivity
XML
文件:
<?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"
android:orientation="vertical"
android:id="@+id/buttonsContainer"
tools:context="com.example.myapplication.MainActivity">
</LinearLayout>
And here's my fragment
XML
code : 这是我的
fragment
XML
代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
What I am trying to do is basically I want to change the button text when it's clicked to something else (it must happen on the parent activity
. 我想要做的基本上是我想在单击按钮时将按钮文本更改为其他内容(它必须在父
activity
发生)。
I already know how to do it in the fragment activity ) . 我已经在片段活动中知道怎么做了。
I also want to set an onClickListner
to that button from MainActivity
and not from the fragment
activity
itself but whenever I try to access that fragment
from the main activity
I get null
value (doesn't matter whether i'm trying to get a reference to its Activity
or View
as in myCar.getActivity()
or MyCar.getView()
) . 我还想从
MainActivity
而不是fragment
activity
本身为该按钮设置onClickListner
,但是每当我尝试从主要activity
访问该fragment
,我都会得到null
值(无论我是否尝试获取对它的引用其Activity
或View
如myCar.getActivity()
或MyCar.getView()
)。
Thanks in advance. 提前致谢。
Logcat : Logcat:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 27060
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Apparently I misunderstood your question. 显然我误解了你的问题。 To access a fragment from parent activity the process is similar and this is a way you can achieve that:
要访问父活动中的片段,过程是相似的,这是您可以实现的方式:
MyFragment myFragment;
myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("MyFragmentTag");
if(myFragment != null && myFragment.isAdded()) // you need to verify if the instance is actually added to the activity
myFragment.submitButton.setText("It works");
Your problem is that when you're creating the fragment in code and adding it the view for the fragment won't be inflated yet so it doesn't exist. 您的问题是,当您在代码中创建片段并将其添加时,该片段的视图不会被夸大,因此它不存在。 If you add Log.v("Trace", "End of onCreate");
如果添加Log.v(“ Trace”,“ onCreate的结尾”); at the end of onCreate and Log.v("Trace", "Car view inflated");
在onCreate和Log.v(“ Trace”,“ Car view inflated”)的末尾; inside the onCreateView for the Car fragment you will see this in action.
在Car片段的onCreateView内,您将看到它的作用。 What you should do is change it so the button text gets changed inside the inflation of the fragment view.
您应该做的是更改它,以便在片段视图的膨胀范围内更改按钮文本。
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_car, container, false); Button b = (Button)rootView.findViewById(R.id.submitButton); b.setText("It works !"); return rootView; }
Try below code for Car Fragment 尝试下面的汽车片段代码
public class Car extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.car, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button b = (Button) view.findViewById(R.id.submitButton); //throws an exception as I'm trying to execute the "findViewById" method on a null object , as the debugger say .
b.setText("It works !"); // it doesn't
}
}
And MainActivity like 和MainActivity一样
public class MainActivity extends AppCompatActivity {
Car myCar = new Car();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.buttonsContainer,myCar,"me").commit();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.