gpt4 book ai didi

java - 显示从edittext到textview的文本

转载 作者:行者123 更新时间:2023-12-02 00:24:23 24 4
gpt4 key购买 nike

我有一个天气应用程序,要求您从编辑文本字段中获取文本并将其显示在 TextView 中,我正在尝试这样做,以便当我输入一个地方时,它会为他们生成随机天气以及显示他们的输入。

除了在线示例之外,我没有尝试太多,因为我最近开始学习 Android 开发。

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

/**
* Implementation for the main activity
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// member variable for the user provided location
private String location;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// get the Get Forecast button
Button btnGetForecast = (Button) findViewById(R.id.btnGetForecast);

// set the click listener to the btnGetForecast Button
btnGetForecast.setOnClickListener(this);

EditText loc = findViewById(R.id.etLocationInput);
location = loc.getText().toString();


}

@Override
public void onClick(View view) {
// view is the View (Button, ExitText, TextView, etc) that was clicked


// if it was the btnGetForecast
if (view.getId() == R.id.btnGetForecast){

}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tvTitle" />

<TextView
android:id="@+id/tvInstructions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter a location below for the forecast" />

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

<Button
android:id="@+id/btnGetForecast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Forecast" />

<TextView
android:id="@+id/tvLocationDisplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="The weather in " />

</LinearLayout>

我希望应用程序显示用户的输入并在 TextView 中显示它

最佳答案

onCreate 中的这一行: 'location = loc.getText().toString()' 只会获取 loc 中的当前文本,在 onCreate 中该文本将是一个空字符串。

您应该查看 TextWatcher:https://developer.android.com/reference/android/text/TextWatcher 。这将允许您在 loc 的文本更改时收到回调,然后您可以执行天气生成。

关于java - 显示从edittext到textview的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com