从一项活动转移到另一项活动时,如何保留editText输入?

时间:2019-04-02 18:50:41

标签: java android android-activity android-edittext android-savedstate

我的一项活动中有一堆EditText。它们在屏幕上可见,用户可以键入它们。用户还可以移动到另一个完全不同的屏幕。但是,当前,如果他/她使用EditTexts返回活动,则他/她的输入将不再显示在[first]屏幕上。

我可以使用什么代码将用户输入保留在第一个屏幕/第一个活动的EditText中?

谢谢。

编辑(仅更新代码)

package com.example.owner.introductoryapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class UserDataInputActivity extends AppCompatActivity
{
    String[] genderOptions = {"Male", "Female"};

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_data_input);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice, genderOptions);
        AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.GenderPromptValue);
        acTextView.setThreshold(1);
        acTextView.setAdapter(adapter);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putString("Agestr",(((EditText) findViewById(R.id.AgePromptValue)).getText().toString()));
        savedInstanceState.putString("Speedstr",(((EditText) findViewById(R.id.GaitSpeedPromptValue)).getText().toString()));
        savedInstanceState.putString("Weightstr",(((EditText) findViewById(R.id.WeightPromptValue)).getText().toString()));
        savedInstanceState.putString("Heightstr",(((EditText) findViewById(R.id.HeightPromptValue)).getText().toString()));
        savedInstanceState.putString("Genderstr",(((EditText) findViewById(R.id.HeightPromptValue)).getText().toString()));
        savedInstanceState.putString("UPDRSstr",(((EditText) findViewById(R.id.UPDRSPromptValue)).getText().toString()));
        savedInstanceState.putString("TUAGstr",(((EditText) findViewById(R.id.TUAGPromptValue)).getText().toString()));
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        ((EditText) findViewById(R.id.AgePromptValue)).setText(savedInstanceState.getString("Agestr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.GaitSpeedPromptValue)).setText(savedInstanceState.getString("Speedstr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.WeightPromptValue)).setText(savedInstanceState.getString("Weightstr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.HeightPromptValue)).setText(savedInstanceState.getString("Heightstr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.HeightPromptValue)).setText(savedInstanceState.getString("Genderstr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.UPDRSPromptValue)).setText(savedInstanceState.getString("UPDRSstr"), TextView.BufferType.EDITABLE);
        ((EditText) findViewById(R.id.TUAGPromptValue)).setText(savedInstanceState.getString("TUAGstr"), TextView.BufferType.EDITABLE);
    }

    public void onGenericMenuClick(View v)
    {
        Intent intent = null;

        ArrayList<String> inputStrings = new ArrayList<>();
        inputStrings.add((((EditText) findViewById(R.id.AgePromptValue)).getText().toString()));
        inputStrings.add((((EditText) findViewById(R.id.GaitSpeedPromptValue)).getText().toString()));
        inputStrings.add((((EditText) findViewById(R.id.WeightPromptValue)).getText().toString()));
        inputStrings.add((((EditText) findViewById(R.id.HeightPromptValue)).getText().toString()));
        if(((EditText) findViewById(R.id.GenderPromptValue)).getText().toString().equals("Male"))
            inputStrings.add("1");
        else //(((EditText) findViewById(R.id.GenderPromptValue)).getText().toString() == "Female")
            inputStrings.add("2");
        inputStrings.add((((EditText) findViewById(R.id.UPDRSPromptValue)).getText().toString()));
        inputStrings.add((((EditText) findViewById(R.id.TUAGPromptValue)).getText().toString()));

        // if you click info buttons (even if the EditTexts are blank) show the Dialogs
        if(v.getId() == R.id.gaitInfoButton || v.getId() == R.id.UPDRSInfoButton || v.getId() == R.id.TUAGInfoButton)
        {
            if(v.getId() == R.id.gaitInfoButton)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(UserDataInputActivity.this);
                builder.setMessage(R.string.GaitInformationContent)
                        .setPositiveButton(R.string.acknowledge, new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id) {}
                        });
                // Create the AlertDialog object and return it
                builder.create().show();
            }
            if(v.getId() == R.id.UPDRSInfoButton)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(UserDataInputActivity.this);
                builder.setMessage(R.string.UPDRSInformationContent)
                        .setPositiveButton(R.string.acknowledge, new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id) {}
                        });
                // Create the AlertDialog object and return it
                builder.create().show();

            }
            if(v.getId() == R.id.TUAGInfoButton)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(UserDataInputActivity.this);
                builder.setMessage(R.string.TUAGInformationContent)
                        .setPositiveButton(R.string.acknowledge, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {}
                        });
                // Create the AlertDialog object and return it
                builder.create().show();
            }
        }//If input fields are blank, refresh the activity
        else if(inputStrings.get(0).matches("") == true
             || inputStrings.get(1).matches("") == true
             || inputStrings.get(2).matches("") == true
             || inputStrings.get(3).matches("") == true
             || inputStrings.get(4).matches("") == true
             || inputStrings.get(5).matches("") == true
             || inputStrings.get(6).matches("") == true)
        {
            Toast.makeText(this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, UserDataInputActivity.class));
        }//if the input fields are filled and you aren't clicking any info buttons, then navigate to whatever, specified page
        else
        {
            if(v.getId() == R.id.pasttests)
                intent =  new Intent(this, PastDiagnosticResult.class);
            else if (v.getId() == R.id.currenttest)
            {
                intent =  new Intent(this, CurrentDiagnosticResultActivity.class);
                intent.putExtra("INPUTVALUE",inputStrings);
            }
            else if (v.getId() == R.id.myinfo)
                intent =  new Intent(this, UserDataInputActivity.class);
            else if(v.getId() == R.id.VoiceTestingPrompt)
                intent =  new Intent(this, SpeechRecognition.class);

            if (intent != null) {
                startActivity(intent);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.owner.introductoryapplication">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android:permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomePageActivity" />

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

        <activity android:name=".UserDataInputActivity" />
        <activity android:name=".CurrentDiagnosticResultActivity" />
        <activity android:name=".PastDiagnosticResult"></activity>
        <activity android:name=".SpeechRecognition"></activity>
    </application>

</manifest>

3 个答案:

答案 0 :(得分:1)

您可以使用onSavedInstanceState

@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
    String message = savedInstanceState.getString("message");
    Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}

来自How to use onSavedInstanceState example please

答案 1 :(得分:0)

您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并保存这样的输入

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
   super.onSaveInstanceState(savedInstanceState);
   savedInstanceState.putString("editTextString", editText.getText().toString());

}

然后您覆盖onRestoreInstanceState(Bundle savedInstanceState)以获得保存状态

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
   super.onRestoreInstanceState(savedInstanceState);
   editText.setText(savedInstanceState.getString("editTextString"), TextView.BufferType.EDITABLE);

}

答案 2 :(得分:0)

另一种方法是SharedPreferences,当重定向另一个活动时,将数据作为打击存储在SharedPreferences中

SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString("Agestr","3");
editor.putString("Speedstr", "22");

editor.commit();

当您回到此屏幕时,从SharedPreferences中获取此数据并填写您的编辑文本

String Agestr = prefs.getString("Agestr", ""); 
((EditText) findViewById(R.id.AgePromptValue)).setText(Agestr )