简体   繁体   English

尝试从父级活动访问片段视图时,为什么会得到空值?

[英]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值(无论我是否尝试获取对它的引用其ActivityViewmyCar.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.

相关问题 活动到片段通信:当我尝试从活动更新片段中的文本视图时,出现空指针异常 - Activity to Fragment Communication: When I tried to update text view in fragment from activity am getting null pointer exception 尝试使用Fragment中的Activity引用时,为什么会出现NullPointerException? - Why am I getting a NullPointerException when trying to use the reference of Activity from a Fragment? 尝试将包从我的活动传递到我的片段时,为什么我不断收到 null? - Why do I keep getting null when trying to pass a bundle from my activity to my fragment? 当我从 Activity 调用到 Fragment 时,Editext 值获取 Null - Editext Value Getting Null when I call from Activity to Fragment 从父活动调用时,片段视图为空 - Fragment View is Null When Called From Parent Activity 尝试从ContentValues对象检索值时为什么会为null? - Why am I getting null when trying to retrieve a value from a ContentValues object? 如何从父活动的片段访问视图? - How do I access a view from a Fragment from the Parent Activity? 尝试从Activity中访问时,Fragment View为null - Fragment View is null when try to access from Activity 从活动向片段传递值时得到空值? - getting null value when passing value from activity to fragment? 为什么我从另一个活动传递的列表中获取空值? - Why I am getting null value from list which is passed from another Activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM