Отображение текста из текста редактирования в текстовое представление - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть приложение погоды, которое требует, чтобы вы взяли текст из поля редактирования текста и отобразили его в текстовом представлении. Я пытаюсь сделать так, чтобы при вводе места он генерировал для них случайную погоду вместе сотображение их входных данных.

Я не очень старался, кроме примеров в Интернете, поскольку недавно начал изучать разработку для 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>

Я ожидаю, что приложение покажет вклад пользователя иотобразить его в виде текста

Ответы [ 2 ]

0 голосов
/ 23 сентября 2019

Ну, все, что вам нужно сделать, это добавить этот код в метод onClick:

@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){
        String text = loc.getText().toString();
        yourTextView.setText(text);
    }
}

И не забудьте сделать переменные представления глобальными, чтобы вы могли получить к ним доступ вне метода onCreate, не используяfindViewById () снова.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private TextView yourTextView;
private EditText loc;

@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);

    loc = findViewById(R.id.etLocationInput);
    yourTextView = findViewById(R.id.tvLocationDisplay);


    }
 ...
}
0 голосов
/ 23 сентября 2019

Эта строка в вашем onCreate: 'location = loc.getText (). ToString ()' будет получать только текущий текст в loc, который в onCreate будет пустой строкой.

Вы должны заглянуть в TextWatcher: https://developer.android.com/reference/android/text/TextWatcher. Это позволит вам получить обратный вызов, когда текст loc изменяется, и вы сможете выполнить генерацию погоды.

...