片段中的Sharedpreference Edittext

时间:2018-10-04 13:22:16

标签: android android-fragments sharedpreferences

到目前为止,我有一个片段,其中有2个edittext和一个按钮。我需要做的是保存在Edittext中编写的文本,以便当我更改为另一个片段然后返回时,我将看到我在Edittexts中编写的最后一句话。

为解决这个问题,我使用了sharedpreference,但是我只能使它与按钮一起使用,以便在按下按钮时保存edittext中的文本,然后在onCreate中的片段中对其进行检索。我想要的是自动更新,所以我不必按任何按钮。

public class KontaktFragment extends Fragment {

private EditText beskedTekst;
private EditText emneTekst;
private Button kontaktSend;

public KontaktFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate( R.layout.fragment_kontakt, container, false );

    beskedTekst = (EditText) view.findViewById( R.id.beskedEdit );
    emneTekst = (EditText) view.findViewById( R.id.emneEdit );
    kontaktSend = (Button) view.findViewById( R.id.kontaktButton );

    hentTekst();

    kontaktSend.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendMail();
        }
    } );
    return view;
}

public void sendMail() {

    String besked = beskedTekst.getText().toString();
    String emne = emneTekst.getText().toString();

    //String recipientList = kontaktTekst.getText().toString();
    //String[] recipients = recipientList.split(",");

    gemTekst();

    Intent intent = new Intent( Intent.ACTION_SEND );
    intent.putExtra( Intent.EXTRA_EMAIL, new String[]{"xxx"} );
    intent.putExtra( Intent.EXTRA_SUBJECT, emne );
    intent.putExtra( Intent.EXTRA_TEXT, besked );

    intent.setType( "message/rfc822" );

    startActivity( Intent.createChooser( intent, "Vælg en email klient" ) );

    intent.setData( Uri.parse( "mailto:" ) );
}

public void gemTekst() {

    String besked = beskedTekst.getText().toString();
    String emne = emneTekst.getText().toString();

    SharedPreferences sp = this.getActivity().getSharedPreferences( "kontakt", 0 );
    SharedPreferences.Editor sedt = sp.edit();
    sedt.putString( "textvalue", besked );
    sedt.putString( "txtopertaive", emne );
    sedt.commit();

}

public void hentTekst() {

    SharedPreferences sp = getActivity().getSharedPreferences( "kontakt", 0 );
    String tValue = sp.getString( "textvalue", "" );
    String tOperative = sp.getString( "txtopertaive", "" );

    beskedTekst.setText( tValue );
    emneTekst.setText( tOperative );   

   }

}

1 个答案:

答案 0 :(得分:2)

在片段中添加onPause生命周期方法并添加所需的方法。

 @Override
public void onPause() {
    super.onPause();
    gemTekst();
}