拯救和在片段之间切换时重新加载edittext值

时间:2016-06-26 10:34:23

标签: java android android-fragments

java& Two.java) 进入每个片段的那里是editext: 一:editText_One 二:editText_Two

当我在片段之间切换时,如何保存和重新调整editText_One(和editText_Two)?

我在读完tutos之后尝试了几件事,但没有什么效果好;(

One.xml

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

    <TextView
        android:id="@+id/tv_one"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="one" />

    <EditText
        android:layout_width="237dp"
        android:layout_height="wrap_content"
        android:inputType="date"
        android:ems="10"
        android:id="@+id/editText_One"
        android:text="blabla"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

Two.xml:

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

    <TextView
        android:id="@+id/tv_one"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TWO" />

    <EditText
        android:layout_width="237dp"
        android:layout_height="wrap_content"
        android:inputT`enter code here`ype="date"
        android:ems="10"
        android:id="@+id/editText_Two"
        android:layout_gravity="center_horizontal" />

One.java:

/**
 * 
 */
package com.example.navigationsubmenu;

/**
 * @author info-medios
 *
 */
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Calendar;

public class One extends Fragment {
//    public static final String EXTRA_URL_nommatiere = "url";
    EditText editText_one;
//    String valeur;
    private  final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";

    public One() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Bundle bundle = new Bundle();
/*        Bundle bundle = getActivity().getIntent().getExtras();
        Bundle mySavedInstanceState = getArguments();

        if (bundle!= null) {// to avoid the NullPointerException
            // editText_one.setText("premiere");
            String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
            editText_one.setText(persistentVariable);
        }*/
        Bundle extras = getActivity().getIntent().getExtras();
        if (extras != null) {
            String persistentVariable = extras.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
            editText_one.setText(persistentVariable);

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.one, container, false);
        //Instancier vos composants graphique ici (faîtes vos findViewById)
        editText_one = (EditText) view.findViewById(R.id.editText_One);             //getview marche aussi





/*        Bundle extras = getActivity().getIntent().getExtras();
        if (extras != null) {
            valeur = extras.getString(EXTRA_URL_nommatiere);                        //Affiche le nom matiere
        }
        else
        {

        }
        editText_one.setText(valeur );*/


        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        String persistentVariable = editText_one.getText().toString();

        Intent intent = new Intent(getActivity(), One.class);
        intent.putExtra(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
        //startActivity(intent);

        getArguments().putString(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
    }

/*    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle extras = getActivity().getIntent().getExtras();
        if (savedInstanceState != null) {
            // Restore last state for checked position.
            valeur = extras.getString(EXTRA_URL_nommatiere);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putString("TEXT", valeur);

    }*/

/*    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.v(TAG, "Inside of onRestoreInstanceState");
        valeur = extras.getString(EXTRA_URL_nommatiere);
    }*/

}

有人可以帮助我吗,

许多thnaks

2 个答案:

答案 0 :(得分:0)

首先你需要将片段附加到activity然后你可以简单地定义两个字符串String one,在包含片段的activity中定义String 2并将每个editText的值分配给不同的一个 即

String one=editTextOne.getText.toString();
String two=editTextTwo.getText.toString();

答案 1 :(得分:0)

当您必须在活动或片段之间切换时,您可以使用共享首选项来存储少量数据并检索它们。

共享首选项是一组小键/值对。

<强>写

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPref.();

              editor.putInt(getString(R.string.saved_high_score), newHighScore);

editor.commit();

<强>读取

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

int defaultValue = getResources().getInteger(R.string.saved_high_score_default);

long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

您可以使用 put [Type] get [Type] 方法编写和读取任何原始数据类型,如字符串。

上面的源代码来自官方Android开发人员培训,属于Android。

&#34;有没有办法使用saveInstanceState?&#34;

我认为当一个活动被屏幕旋转破坏并创建或在调用后恢复时,此捆绑包很有用,但在活动和碎片之间切换时则不然。

但你可以尝试一下。我知道带有id的EditText这样的视图有一个内置的saveInstanceState,所以你不必手动处理它。

要在片段之间切换,您可以使用活动类作用域属性。您需要向片段添加接口以允许它们与活动进行通信。

实施例

Overview

以下示例显示如何在片段之间切换并保留EditText值。

MainActivity包含一个FrameLayout和两个按钮。片段事务在按钮单击事件上完成。

片段包含与活动通信的接口。每次更改EditText值时,都会更新活动的属性。

活动与片段通信,以便在事务发生后立即设置EditText值。

首先,这里是MainActivity,FragmentA和FragmentB类的xml布局文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="morbak.stackoverflow.fragmentcommunication.MainActivity">

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="50"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="50"
        android:orientation="horizontal"
        android:weightSum="100">

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:text="Fragment A" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:text="Fragment B" />

    </LinearLayout>

</LinearLayout>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Fragment A content"/>

</LinearLayout>

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etTwo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Fragment B content"/>

</LinearLayout>

fragment_b.xml

然后,这里是片段A和B类。源代码是不言自明的。

package morbak.stackoverflow.fragmentcommunication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class FragmentA extends Fragment {

    //Views
    EditText etOne;

    //Fields
    String value;

    //Listeners
    OnFragmentASelectedListener mCallback;

    //Context
    Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //Inflate views and layouts
        View rootView = inflater.inflate(R.layout.fragment_a, container, false);

        etOne = (EditText) rootView.findViewById(R.id.etOne);

        //Events
        etOne.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                //Execute the interface's abstract method
                mCallback.onFragmentASelected(s.toString());

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etOne.setText(value);

        return rootView;
    }

    //Set the fragment's field value
    public void setEditText(String newValue) {

        value = newValue;

    }

    //Interface
    public interface OnFragmentASelectedListener {
        public void onFragmentASelected(String value);
    }

    //Throws an exception if the activity implements FragmentA.OnFragmentASelectedListener, but not the abstract method
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        context = activity;

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnFragmentASelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentASelectedListener");
        }
    }
}

FragmentA.java

使用FragmentB应该完成同样的工作,但你显然必须搜索 FragmentA 并将 FragmentB etOne 替换为 etTwo

最后,这是MainActivity处理片段事务并使用片段&#39;听众:

package morbak.stackoverflow.fragmentcommunication;

import android.content.Context;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements FragmentA.OnFragmentASelectedListener, FragmentB.OnFragmentBSelectedListener {

    Button button1;
    Button button2;

    FragmentTransaction transaction;
    FragmentA fragmentA;
    FragmentB fragmentB;

    String editTextOne;
    String editTextTwo;

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

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);

        editTextOne = "";
        editTextTwo = "";

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                transaction = getSupportFragmentManager().beginTransaction();

                fragmentA = new FragmentA();

                transaction.replace(R.id.fragment_container, fragmentA);
                transaction.addToBackStack(null);
                transaction.commit();

                fragmentA.setEditText(editTextOne);

            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                transaction = getSupportFragmentManager().beginTransaction();

                fragmentB = new FragmentB();

                transaction.replace(R.id.fragment_container, fragmentB);
                transaction.addToBackStack(null);
                transaction.commit();

                fragmentB.setEditText(editTextTwo);

            }
        });
    }

    public void onFragmentASelected(String value) {
        editTextOne = value;
    }

    public void onFragmentBSelected(String value) {
        editTextTwo = value;
    }
}

MainActivity.java