Android:即使在 setContentView 之后,findViewById 也会返回 Null [英] Android: findViewById returns Null even if is after setContentView

查看:39
本文介绍了Android:即使在 setContentView 之后,findViewById 也会返回 Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 LoginActivity 中的代码:

Here's my code in LoginActivity:

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

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

    loginButton = (Button)findViewById(R.id.loginButton);

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onLoginButtonClicked();
        }
    });

    // Check if there is a currently logged in user
    // and they are linked to a Facebook account.
    ParseUser currentUser = ParseUser.getCurrentUser();
    if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser)) {
        // Go to the main activity
        showHomeActivity();
    }
}

在 fragment_login.xml 中

in fragment_login.xml

<Button
    android:id="@+id/loginButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/login_button" />

这是我运行应用程序时的日志:

And this is the log when i run the application:

E/AndroidRuntime(6647): FATAL EXCEPTION: main
E/AndroidRuntime(6647): Process: com.moostachestudio.drinkitapp, PID: 6647
E/AndroidRuntime(6647): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.moostachestudio.drinkitapp/com.moostachestudio.drinkitapp.LoginActivity}: java.lang.NullPointerException
E/AndroidRuntime(6647):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime(6647):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(6647):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(6647):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(6647):     at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(6647):     at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(6647):     at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(6647):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(6647):     at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(6647):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(6647):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(6647):     at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(6647): Caused by: java.lang.NullPointerException
E/AndroidRuntime(6647):     at com.moostachestudio.drinkitapp.LoginActivity.onCreate(LoginActivity.java:45)
E/AndroidRuntime(6647):     at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime(6647):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(6647):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
E/AndroidRuntime(6647):     ... 11 more

问题是loginButton"是NULL,但我不知道为什么,因为我在setContentView之后调用了findViewById!

The problem is that "loginButton" is NULL but i don't know why, because i call the findViewById after the setContentView!

推荐答案

看来你的 Button 在片段布局中,所以 你的点击方法可能在你的片段中 (PlaceholderFragment) 而不是您的活动.您需要声明另一个 Class extends with Fragment..

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

首先,创建一个名为 PlaceHolderFragment 的新类.用 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.

然后,您的 MainActivity(名为 activity_main)的布局活动可能有一个 FrameLayout,其 id 容器如下所示:

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>  

最后,您的 MainActivity 将只有:

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
}

这篇关于Android:即使在 setContentView 之后,findViewById 也会返回 Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆