findViewById为EditText返回null
findViewById
为EditText
返回null
Java代码:
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代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<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>
任何帮助表示赞赏。
确保setContentView(R.layout.main);
设置为正确的布局。 如果你已经做了一个新的(包括上面的XML代码),然后使用它来设置内容视图 - setContentView(R.layout.your_xml_filename);
在您的视图中更改这些行
android_id="@+id/websiteurlheading"
android_id="@+id/etext"
并改变查看ID像这样
android:id="@+id/websiteurlheading"
android:id="@+id/etext"
例如
<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"
/>
几秒钟前我遇到了这个问题,并且我搜索了一些Stackoverflow帖子。 尽管我自己找到了解决方案。
只要确保你没有调用editText.getText().toString();
在onCreate方法中。 因为它只会返回预加载的值。因此,在这种情况下,editext将始终返回null。