How to get TextView from another Activity without

2019-07-16 04:48发布

I have a TextView in Activity A and that is where the user spends most of the time on the app. My app uses Shared Preferences to save a TextView in Activity C. How do I get the TextView from Activity C without going to activity C when I load Activity A and/or B. I know I can get the TextView from Activity C with intent but I think that only works if I'm coming from Activity C which I am not.

Activity A currently get's the TextView this way

Intent id = getIntent();
if (id.getCharSequenceExtra("idid") != null) {
final TextView setmsg = (TextView)findViewById(R.id.loginid2);
setmsg.setText(id.getCharSequenceExtra("idid"));                

}

But this only works if another Activity used putExtra to get it there.

3条回答
一夜七次
2楼-- · 2019-07-16 05:15

You don't get the TextView but a String preference:

public static void setLangName(Context context, String name) {
    SharedPreferences.Editor editor = context.getSharedPreferences(
            FILE_NAME, Context.MODE_PRIVATE).edit();
    editor.putString(KEY_LANG_NAME, name);
    editor.commit();
}

public static String getLangName(Context context) {
    return context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
            .getString(KEY_LANG_NAME, null);
}

In your activity's layout you put a TextView and setText with the preference value

查看更多
叛逆
3楼-- · 2019-07-16 05:18

You can't save a View instance with Sharedpreferences. Only primitive types can be saved in SharedPreferences. See the SharedPreferences.Editor's put methods.

To pass yourTextView's String value from one Activity to another, either

  • save it in Activity A using editor.putString(...) and retrieve it in Activity B, or
  • pass it between the Activities in an Intent.
查看更多
成全新的幸福
4楼-- · 2019-07-16 05:24

From the question, what I understood is,

Whenever I load Activity A / B , its Text will show the value from Activity C. Isn't it?

Of course we can use SharedPreference. try this:

inside Activity C ->

textview.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ActivityC.this);
SharedPreferences.Editor editor = pref.edit();
    editor.putString("idid", ""+s);
    editor.commit();

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

And now, inside Activity A onCreate ->

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ActivityA.this);
setmsg.setText(pref.getString("idid", "null"));

Thats it.

查看更多
登录 后发表回答