gpt4 book ai didi

android - findViewById 为 EditText 返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:53 25 4
gpt4 key购买 nike

findViewByIdEditText 返回空值

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 代码),则使用它来设置内容 View - setContentView(R.layout.your_xml_filename);

关于android - findViewById 为 EditText 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6487509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com