Android Activity findviewbyid() is null

做~自己de王妃 提交于 2020-01-11 08:45:31

问题


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

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

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


回答1:


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

Why do I need that?

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.

Therefore you should add a layout after the call to super.onCreate()

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

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



回答2:


You need to set your layout

setContentView(R.layout.main_layout);



回答3:


Next code solves the issue (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();

        ...
   }


来源:https://stackoverflow.com/questions/10735887/android-activity-findviewbyid-is-null

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