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

问题描述 投票:0回答:3

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

我可以使用哪些代码在第一个屏幕/第一个活动的EditTexts中保留用户输入?

提前致谢。

编辑(刚更新的代码)

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>
java android android-activity android-edittext android-savedstate
3个回答
1
投票

您可以使用onSaveInstanceState

@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


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

}

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 )
© www.soinside.com 2019 - 2024. All rights reserved.