android 从Activity onCreate访问fragment_main. xml中的片段视图时出现NullPointerException

dw1jzc5e  于 2023-05-27  发布在  Android
关注(0)|答案(4)|浏览(139)

更新我的ADT后我真的很沮丧。以前一个新的Android项目只包含activity_main.xml文件,我们在其中添加了我们的界面元素。现在更新ADT后,每当我创建一个新的Android项目时,它都会创建一个fragment_main.xml沿着activity_main.xml文件。什么是fragment_main.xml?此外,MainActivity.class还包含一些额外的代码,比如一个名为PlaceholderFragment的类和一些其他奇怪的东西。
现在的主要问题是我甚至不能为fragment_main.xml中的按钮添加onClickListener

fragment_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.cameraproject.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="188dp"
        android:text="Button" />

</RelativeLayout>

MainActivity.class:

package com.example.cameraproject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener {
    public static Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }

        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            Toast.makeText(this, "Its working", Toast.LENGTH_SHORT).show();
            break;
        }
    }

}

错误日志:

04-22 11:16:54.186: E/AndroidRuntime(17336): FATAL EXCEPTION: main
04-22 11:16:54.186: E/AndroidRuntime(17336): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cameraproject/com.example.cameraproject.MainActivity}: java.lang.NullPointerException
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.access$700(ActivityThread.java:168)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.os.Looper.loop(Looper.java:137)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.main(ActivityThread.java:5493)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at java.lang.reflect.Method.invokeNative(Native Method)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at java.lang.reflect.Method.invoke(Method.java:525)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at dalvik.system.NativeStart.main(Native Method)
04-22 11:16:54.186: E/AndroidRuntime(17336): Caused by: java.lang.NullPointerException
04-22 11:16:54.186: E/AndroidRuntime(17336):    at com.example.cameraproject.MainActivity.onCreate(MainActivity.java:28)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.Activity.performCreate(Activity.java:5372)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-22 11:16:54.186: E/AndroidRuntime(17336):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
tkqqtvp1

tkqqtvp11#

试试这个。
你的按钮属于fragment_main.xml,所以你必须在PlaceholderFragment中初始化它

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }
    Button b;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Its working", Toast.LENGTH_SHORT).show();
        }
    });
        return rootView;
    }
}
z6psavjg

z6psavjg2#

您已经将布局文件设置为activity_main.xml ..但您已经在fragment_main.xml中添加了按钮..这就是引发空指针异常的原因..
替换这个

setContentView(R.layout.activity_main);

setContentView(R.layout.fragment_main);

这是最简单的解决办法。。

fragment_main.xml中的全部内容复制到activity_main.xml ...
希望有帮助。

mbyulnm0

mbyulnm03#

替换此行
setContentView(R.layout.activity_main);
关于setContentView(R.layout.fragment_main);

pkmbmrz7

pkmbmrz74#

你的按钮属于片段的布局而不是你的活动的布局。因此,从activitie的onCreate()中删除按钮视图初始化代码并添加
View rootView = inflater.inflate(R.layout.fragment_main, container, false); Button b = (Button) rootView.findViewById(R.id.button1);
在占位符片段的onCreateView()中。

相关问题