findViewById为的EditText返回null [英] findViewById returns null for EditText

查看:150
本文介绍了findViewById为的EditText返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


public class MainActivity extends Activity
{
     private EditText editText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        editText = (EditText) findViewById(R.id.etext);
        if(editText == null)
        {
            Log.v("editText", "booohooo");
        }
        else
        {
            Log.v("editText", "Success");
        }

        final Button button = (Button) findViewById(R.id.gobutton);

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) 
            {
                 if(editText != null)
                 {
                    Log.v("editText", "is not NULL");
                 }
                 else
                 {
                    Log.v("editText", "is NULL :(");
                 }

                // Perform action on click
                if(editText != null)
                {
                    editText.getText();
                }
                else
                {
                    Log.v("editText", "is NULL");
                }
                Log.v("url", editText.getText().toString().trim());
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(editText.getText().toString().trim()));
                startActivity(browserIntent);
            }
        });
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android_id="@+id/websiteurlheading"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Enter web site URL"
    />
<EditText android_id="@+id/etext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:layout_below="@id/websiteurlheading"
    />
<Button android:id="@+id/gobutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter" 
    />
</LinearLayout>

任何帮助是AP preciated。

Any help is appreciated.

推荐答案

确保的setContentView(R.layout.main); 设置为正确的布局。如果你做了一个新的(包括上面的XML code),然后用它来设置内容视图 - 的setContentView(R.layout.your_xml_filename);

Make sure that setContentView(R.layout.main); is set to the correctly layout. If you have made a new one (which includes that xml code above) then use that to set the content view - setContentView(R.layout.your_xml_filename);

这篇关于findViewById为的EditText返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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