Android Activity findviewbyid() 为空 [英] Android Activity findviewbyid() is null

查看:34
本文介绍了Android Activity findviewbyid() 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class FileExplorerActivity extends Activity 
{
    public static final String TAG="ricky";
    Button button;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        button = (Button) findViewById(R.id.but);<<<------------------
        if(button == null)
        Log.d(TAG, "FileExplorerActivity: button is null");
    }
    public FileExplorerActivity()
    {
       Log.d(TAG, "FileExplorer: constructor()");
    }
}

这是一个简单的 Activity,它被另一个使用 Intent 的 Activity 带到前面

This is a simple Activity which is brought in front by another activity using Intent

Intent openFileBrowser = new Intent(this, FileExplorerActivity.class);
try
{
    startActivity(openFileBrowser); 
}

运行代码后,我的 LogCat 文件显示button is null"为什么???

After running the code my LogCat file says "button is null" Why ???

推荐答案

正如其他人所说,你没有通过 setContentView() before 调用 设置布局>findViewById().

As others stated, you didn't set a layout via setContentView() before calling findViewById().

我为什么需要那个?

因为 Activity.findViewById() 在当前活动的视图层次结构中搜索.如果您不设置视图层次结构,则找不到任何内容.当这个方法什么也没找到时,它返回null.

Because Activity.findViewById() searches in the view hierachy of the current activity. If you set no view hierachy, there is nothing to find. And when this method finds nothing, it returns null.

因此您应该在调用 super.onCreate()

super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);

button = (Button) findViewById(R.id.but);
// ... 

这篇关于Android Activity findviewbyid() 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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