Android: findViewById returns Null even if is after setContentView

陌路散爱 提交于 2019-11-28 14:23:56

It seems that your Button is in fragment layout, so your on click method might be in your fragment (PlaceholderFragment) instead of your activity. You need to declare another Class extends with Fragment..

First, create a new Class named PlaceHolderFragment. Extend it with Fragment and add this code below to it:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_login, container, false);
    // ...
    loginButton = (Button) rootView.findViewById(R.id.loginButton);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onLoginButtonClicked();
        }
    });
    // ...
    return rootView;
}  

// put your method onLoginButtonClicked here.

Then, your layout activity for MainActivity (named activity_main) might have a FrameLayout with the id container like this:

<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=".MainActivity" >

    <!-- other views -->

</FrameLayout>  

Finally, your MainActivity will only have:

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

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

    // ... without loginButton
    // and some more stuff
}

Try declaring the button inside onCreate, rather than declaring it outside of it (which is what I'm assuming you're doing).

Oh, and if you haven't tried this already, use "VIEW.findViewById(R.id.loginButton)", rather than just "findViewById(R.id.loginButton);". I think that's more likely your problem; I forget about it a lot too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!