Button button = findViewById(R.id.button) 在 Android Studio 中始终解析为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21736187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:59:24  来源:igfitidea点击:

Button button = findViewById(R.id.button) always resolves to null in Android Studio

androidandroid-studio

提问by sunny24365

I'm new to Android development and Android Studio, so pardon my ignorance.

我是 Android 开发和 Android Studio 的新手,请原谅我的无知。

findViewByIdof a button I added always resolves to null. Hence if I try to setonClickListenerit fails the whole Activity.

findViewById我添加的按钮总是解析为null. 因此,如果我尝试setonClickListener使整个活动失败。

MainActivity:

主要活动:

public class MainActivity extends ActionBarActivity {

    @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();
        }

        Button buttonClick = (Button) findViewById(R.id.button);
        buttonClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onButtonClick((Button) view);
            }

        });

    }

    public void onButtonClick(Button view) {
        TextView textHello = (TextView) findViewById(R.id.textView);
        textHello.setText("Clicked !!!");
    }


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

}

activity_main.xml

活动_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pluralsight.activitylifecycle.MainActivity"
tools:ignore="MergeRootFrame" />

fragment_main.xml

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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.pluralsight.activitylifecycle.MainActivity$PlaceholderFragment">

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/buttonClick"
    android:id="@+id/button"
    android:layout_below="@+id/textView"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="54dp" />

</RelativeLayout>

回答by Andy Res

This is because findViewById()searches in the activity_mainlayout, while the button is located in the fragment's layout fragment_main.

这是因为findViewById()activity_main布局中搜索,而按钮位于片段的布局中fragment_main

Move that piece of code in the onCreateView()method of the fragment:

onCreateView()在片段的方法中移动那段代码:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootViewview:

请注意,现在您可以通过rootView视图访问它:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

否则你会再次得到 NullPointerException。

回答by BigT

The button code should be moved to the PlaceholderFragment()class. There you will call the layout fragment_main.xmlin the onCreateViewmethod. Like so

按钮代码应该移到PlaceholderFragment()类中。在那里,您将fragment_main.xmlonCreateView方法中调用布局。像这样

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    Button buttonClick = (Button) view.findViewById(R.id.button);
    buttonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onButtonClick((Button) view);
        }

    });

    return view;
}

回答by FD_

R.id.buttonis not part of R.layout.activity_main. How should the activity find it in the content view?

R.id.button不是 的一部分R.layout.activity_main。活动应该如何在内容视图中找到它?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

包含按钮的布局由 Fragment 显示,因此您必须在 Fragment 中获取 Button。