我有一些 Java 经验,但我现在正在尝试创建一个 Android 应用程序,但我不知道如何接受用户输入。我的编辑文本的id是enterRequestMessage,我的XML文件的名称是activity_score_entry.xml。这是我的 Java 文件的开头。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ScoreEntry extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
}
}
最佳答案
您需要访问 xml 中的控件
public class ScoreEntry extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
String value = editText.getText().toString();
// use the value here
Log.d(ScoreEntry.class.getCanonicalName(), "The value is: " + value);
}
}
}
在 xml 中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_score_entry"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
您可以根据需要调整代码。
关于java - 接受来自 Activity 的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444206/