dan*_*c05 0 string android 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我在主布局文件上创建了一个EditText View.这是使用userText标识符引用的.由于它是一个EditText字段,用户可以随时修改其中的文本; 我想要完成的是检索用户在点击标识为getToast的按钮时输入的文本,然后将其显示为Toast.
我现在正在使用Resources类(我的第一个猜测?)来检索存储在toastText下的String,但是这是无用的,因为它正在提取存储在main.xml中的文本 - 这是空的,因为我声明没有"android :text"该视图的属性,而不是我使用"android:hint"告诉用户输入文本.
我读过有关意图的内容,但如果我要将字符串发送到另一个活动,而不是同一个活动,那就有意义了.我曾经认为这是一项简单的任务,但是我有更多的时间,我有希望:P
BTW:
该getToast方法被定义为"机器人:OnClickMethod"用于在XML中创建的按钮.它可以与任何其他文本字符串一起使用.
有任何想法吗?
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您只需getText()在TextView上调用该函数即可.
例:
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();
}
Run Code Online (Sandbox Code Playgroud)
此代码将显示一个Toast,其中包含EditText中的文本可用,以及toast未输入任何内容时资源中的默认文本.