java - 接受来自 Activity 的用户输入

标签 java android

我有一些 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/

相关文章:

android - 导出后未在 Honeycomb 上调用 BOOT_COMPLETED

java - 如何在spring MVC中获取应用程序路径

java - MPAndroidChart:为 Y 轴提供一些偏移量

java - 我从 UI 中的日历获取日期,格式为 dd/mm/yyyy。但我想要 18 年 7 月 12 日的格式

android - 有谁知道如何使用 monkeyrunner 锁定屏幕?

android - 如何在android中以编程方式更改应用程序小部件中的图像

android - 如何将后退按钮事件从 phonegap 发送到 ember 应用程序?

Android Studio Stuck at Gradle 下载创建新项目

java - Webview 打开浏览器即使覆盖

java - 检测新的 HttpSession