繁体   English   中英

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

[英]Why am I getting a null value when trying to access a fragment view from the parent activity?

首先,我知道以前有很多类似的问题要问,但是没有一个回答我的问题。

我会保持简单。

我有一个名为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
    }
}

并且我有一个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;
    }
}

除了显示与之对应的布局外,它什么也不做。

这是我的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>

这是我的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>

我想要做的基本上是我想在单击按钮时将按钮文本更改为其他内容(它必须在父activity发生)。

我已经在片段活动中知道怎么做了。

我还想从MainActivity而不是fragment activity本身为该按钮设置onClickListner ,但是每当我尝试从主要activity访问该fragment ,我都会得到null值(无论我是否尝试获取对它的引用其ActivityViewmyCar.getActivity()MyCar.getView() )。

提前致谢。

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)

显然我误解了你的问题。 要访问父活动中的片段,过程是相似的,这是您可以实现的方式:

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");

您的问题是,当您在代码中创建片段并将其添加时,该片段的视图不会被夸大,因此它不存在。 如果添加Log.v(“ Trace”,“ onCreate的结尾”); 在onCreate和Log.v(“ Trace”,“ Car view inflated”)的末尾; 在Car片段的onCreateView内,您将看到它的作用。 您应该做的是更改它,以便在片段视图的膨胀范围内更改按钮文本。 @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; }

尝试下面的汽车片段代码

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
    }
}

和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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM