Android FindViewById返回空EditText
我对findViewById()函数有一个常见问题,它返回null:Android FindViewById返回空EditText,android,Android,我对findViewById()函数有一个常见问题,它返回null: <EditText android:id="@+id/nameText" /> <Button android:text="Save" android:onClick="buttonClick1" /> </TableRow android:onClick="buttonClick1" /> 在buttonClick1()中,findViewById()
<EditText
android:id="@+id/nameText"
/>
<Button
android:text="Save"
android:onClick="buttonClick1"
/>
</TableRow
android:onClick="buttonClick1"
/>
在buttonClick1()中,findViewById()返回null。请解释原因?删除
setContentView(视图)代码>从按钮单击1
方法
并通过删除视图以这种方式初始化所有文本视图。
EditText nameText = (EditText) findViewById(R.id.nameText);
EditText lastNameText = (EditText) findViewById(R.id.lastNameText);
EditText indexNumberText = (EditText) findViewById(R.id.indexNumberText);
还可以通过为控件指定高度
和宽度
来正确初始化xml中的控件尝试用以下代码替换您的代码:
public class Activity1 extends ActionBarActivity {
@
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity1);
EditText nameText = (EditText) findViewById(R.id.nameText);
EditText lastNameText = (EditText) findViewById(R.id.lastNameText);
EditText indexNumberText = (EditText) findViewById(R.id.indexNumberText);
}
public void buttonClick1(View view) {
//Your stuff
Log.d(">>>> ", nameText.getText().toString());
}
}
由于现在是您尝试过的正常代码,如果您想设置单击按钮,则必须将其声明为:
Button button1 = (Button) findViewById(R.id.button1);
然后您可以执行以下操作:
public void buttonClick1(View v) {
// Your stuff
}
编辑
确保您的XML上有所有EditText
和所有按钮
,例如:或者,也确保您有一个android:id=“@+id/yourID
在你所有的东西中…,顺便说一句,你可以用它来使用onClick监听器,而不是XML
中的onClick
方法
第1点至第3点应位于onCreate
的内部,第4点应位于onCreate
的外部
1.-在活动中实现View.OnClickListener
public class Activity1 extends ActionBarActivity implements View.OnClickListener {
2.申报
Button button1 = (Button) findViewById(R.id.button1);
3.设置ClickListener
如下:
button1.setOnClickListener(this);
4.-创建一个OnClick
方法:
@Override
public void onClick(View view) {
if (View.equals(button1))
//Your stuff
}
多个问题,除非您没有发布所有代码
1) 在XML中,您关闭了一个TableRow
标记,但我没有看到您打开它。可能只是懒拷贝粘贴
2) 在onCreate
中,您似乎缺少按钮的侦听器。没有任何迹象表明你在任何地方都有按钮。您需要找到按钮的视图,如下所示:
Button button = (Button) findViewById(R.id.nameOfButton);
然后您需要为它设置一个侦听器,如下所示:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Here goes whatever should happen when you click the button.
}
});
3) 至于您的按钮clik1
方法,请将其删除。看起来您正试图创建一个侦听器,但它与它应该的样子相差甚远。正确地说,xml是什么意思。哪里是我不能粘贴更多的代码,不要让me@akcza查看我的编辑,让我知道它是否有效:)@akcza,如果我的答案有助于您将其标记为正确,请将所有初始化移到onCreate()
@akcza:)
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Here goes whatever should happen when you click the button.
}
});