如何从EditText视图中提取文本 - Android

时间:2012-06-12 19:35:05

标签: android string android-edittext

所以我猜这很简单,因为使用getText()来检索信息:)

以下是它的结束:

public void getToast(View v) {
    EditText et = (EditText) findViewById(R.id.userText);
    String toastText = et.getText().toString();
    if (toastText == "" || toastText == null) {
        Toast.makeText(this, "This is a nice toast!", Toast.LENGTH_SHORT).show();   
    }
    else {
    Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show();
    }
}

我在主布局文件上创建了一个 EditText 视图。使用 userText 标识符引用它。由于它是 EditText 字段,用户可以随时修改其中的文本;我想要完成的是检索用户在点击标识为 getToast 的按钮时输入的文本,然后将其显示为Toast。

我现在正在使用Resources类(我的第一个猜测?)来检索存储在 toastText 下的字符串,但这没用,因为它正在提取存储在main.xml中的文本 - 这是空的,因为我声明该视图没有“android:text”属性,而是使用“android:hint”告诉用户输入文本。

我读过有关意图的内容,但如果我要将字符串发送到另一个活动,而不是同一个活动,那就有意义了。我认为这是一项简单的任务,但是我有更多的时间,我有希望:P

BTW:

getToast 方法被定义为在XML上创建的按钮的“android:OnClickMethod”。它可以与任何其他文本字符串一起使用。

有什么想法吗?

package com.testlabs.one;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

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

public void getToast(View v) {
    Resources myResources = getResources();
    String toastText = myResources.getString(R.string.toast); 
    if (toastText == "" || toastText == null) {
        Toast.makeText(this, "This is a nice toast!", Toast.LENGTH_SHORT).show();   
    }
    else {
    Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show();
    }
}
}

3 个答案:

答案 0 :(得分:5)

您只需在TextView上调用函数getText()

示例:

public void getToast( View v )
{
    String toastText = ( (EditText)v ).getText();
    if ( toastText.length() == 0 ) {
        toastText = getResources().getString( R.string.toast );
    }
    Toast.makeText( this, toastText, Toast.LENGTH_SHORT ).show();
}

此代码将在EditText中显示带有文本的Toast,并在输入任何内容时显示toast资源中的默认文本。

答案 1 :(得分:0)

如果您只想通过Intent将一个字符串从一个活动发送到另一个活动

Intent intent = new Intent();
intent.putExtra("key","stringValue");
startActivity(intent);

然后在你的其他活动中

Intent intent = getIntent();
String value = intent.getStringExtra("key","defaultstring");

答案 2 :(得分:0)

我想这个:

EditText et = (EditText) findViewById(R.id.userText);
String toastText = et.getText().toString();

应该是这样的:

String toastText  = findViewById(R.id.userText).toString();

如果没有,我想知道为什么你需要使用中间阶段而不是直接将其转换为java String对象