【问题标题】:saving & reloading edittext value when switching between fragments在片段之间切换时保存和重新加载edittext值
【发布时间】:2016-06-26 10:34:22
【问题描述】:

java & Two.java) 每个片段都有edittext: 一:editText_One 二:editText_Two

当我在片段之间切换时,如何保存和恢复editText_One(和editText_Two)?

我在阅读 tutos 后尝试了几件事,但都没有奏效;(

一个.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>

两个.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" />

一个.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);
    }*/

}

谁能帮帮我,

很多问题

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

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

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

    【讨论】:

    • 你有什么例子吗?
    • 一,二应该是活动中的全局变量,意味着定义出任何方法,即您定义 String one="",String two="";并在附加每个片段时分配它: one=editTextOne.getText.toString();二=editTextTwo.getText.toString();您也可以使用共享首选项。
    【解决方案2】:

    当您必须在 Activity 或 Fragment 之间切换时,您可以使用 Shared Preferences 来存储少量数据并检索它们。

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

    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。

    “saveInstanceState 有办法吗?”

    我认为当一个活动被屏幕旋转销毁和创建或在调用后恢复时,这个包很有用,但在活动和片段之间切换时不是。

    但是你可以试试。我知道像 EditText 这样带有 id 的视图具有内置的 saveInstanceState,因此您不必手动处理它。

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

    示例

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

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

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

    Activity 与 Fragment 通信以在事务后立即设置 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

    然后,这里是 Fragments 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:

    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

    【讨论】:

    • 好的,它与 sharedpreferences 一起使用,但它并不是真正为此而设计的。 Bundle savedInstanceState 没有解决方案?
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多