Android Can';无法从edittext获取文本?

Android Can';无法从edittext获取文本?,android,android-edittext,Android,Android Edittext,我已经更新到ADT版本20。之后我就不能用编辑文本了。对于API级别16,它显示了一些错误。对于较低的API级别,没有错误,但我无法获得EditText的输入。它显示一个空结果 我使用的示例代码: java代码 public class sample extends Activity { EditText edt; Button btn; TextView txt; String str; @Override public void onCreate(Bundle savedInstanceSt

我已经更新到ADT版本20。之后我就不能用编辑文本了。对于API级别16,它显示了一些错误。对于较低的API级别,没有错误,但我无法获得EditText的输入。它显示一个空结果

我使用的示例代码:

java代码

public class sample extends Activity {
EditText edt;
Button btn;
TextView txt;
String str;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    edt = (EditText) findViewById(R.id.editText1);
    btn = (Button) findViewById(R.id.button1);
    txt = (TextView) findViewById(R.id.textView2);
    str = edt.getText().toString();
    btn.setClickable(true);
    btn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Log.d("WordWeb","entered - "+str);
            txt.setText("you entered"+str);
        }
    });
}
}
XML编码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Search"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10" />



<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10pt"
    android:text="Button" />


<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />


实际上,您正在尝试从活动的
onCreate()
中的
EditText
获取文本,该活动尚未包含任何文本

所以只要把这行代码放进去,
str=edt.getText().toString()在按钮的click()中,您将得到结果

比如

btn.setClickable(true);
btn.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        str = edt.getText().toString();
        Log.d("WordWeb","entered - "+str);
        txt.setText("you entered"+str);
    }
});

我认为您正在尝试在
onCreate()
中获取
EditText
(即edt)值,并且我认为您是在完成
onCreate()
方法后输入值。因此,这意味着您的
str
没有获取值


这就是为什么您无法将语句的值设置为
TextView
str=edt.getText().toString()
应该在
onClick
处理程序中。

代码无法访问该值,因为
onCreate
结束后,在
EditText
abd
str
中找到的值超出范围。所以把
str=edt.getText().toString()放在onClick
中的code>语句,以便用户单击按钮时可以访问该值

只需将文本放在按钮内,否则它将不起作用,因为无论你在字符串中得到什么,它也会像你只是cre一样工作

请不要在SO中使用俚语(请不要在SO中使用俚语)。