简体   繁体   English

Android Activity findviewbyid() 为空

[英]Android Activity findviewbyid() is null

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

This is a simple Activity which is brought in front by another activity using Intent这是一个简单的 Activity,它被另一个使用 Intent 的 Activity 带到前面

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

After running the code my LogCat file says "button is null" Why ???运行代码后,我的 LogCat 文件显示“按钮为空”为什么???

As others stated, you didn't set a layout via setContentView() before calling findViewById() .正如其他人所说,调用findViewById()之前,您没有通过setContentView()设置布局。

Why do I need that?为什么我需要那个?

Because Activity.findViewById() searches in the view hierachy of the current activity.因为Activity.findViewById()在当前活动的视图层次结构中搜索。 If you set no view hierachy, there is nothing to find.如果您不设置视图层次结构,则找不到任何内容。 And when this method finds nothing, it returns null.当这个方法没有发现任何东西时,它返回 null。

Therefore you should add a layout after the call to super.onCreate()因此你应该在调用super.onCreate()之后添加一个布局

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

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

你需要设置你的布局

setContentView(R.layout.main_layout);

Next code solves the issue (Xamarin Android)下一个代码解决了这个问题(Xamarin Android)

public class MainActivity : WearableActivity
{
    ...

    OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        **SetContentView(Resource.Layout.RoundMain);**

        // Does not return null anymore:

        FindViewById<Button>(Resource.Id.ButtonVgOk).LongClick += (s, e) => ButtonVgOkOnLongClick();

        ...
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM