EdittextPreference设置自定义TextView

时间:2018-04-02 11:36:20

标签: android

我的TextView上有一个MainActivity这是一个欢迎文字,它的条件是如果我的应用程序的用户没有设置用户名,它只会显示“welcome”,如果用户已设置其用户名,它将显示“欢迎”文本及其已分配的用户名。

我在这个原因中使用EdittextPreference & SharedPreference 问题是,即使已经设置了用户名,它似乎还没有被设置,因为它不会触发我在MainActivity和amp;之间写的if else条件。设置,它仍然显示唯一的“欢迎”文本。 我需要一些线索..

我的MainActivity.java>> https://paste.ubuntu.com/p/2n33ZzVkY4/

my Settings.java>> https://paste.ubuntu.com/p/JBWSqJfmG6/

3 个答案:

答案 0 :(得分:0)

您需要在共享偏好中保存数据并检查共享偏好中是否存在任何数据,然后显示welcome +其用户名

答案 1 :(得分:0)

您正在将数据保存在SharedPreferences上。

您应该使用以下代码从sharedPreferences获取数据。

SharedPreferences sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPreference.getString("username", "");

答案 2 :(得分:0)

请尝试以下完整示例:

1)DemoActivity.class --------

public class DemoActivity extends AppCompatActivity{

private TextView tv;
private SharedPreferences demo_preferences;

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

    demo_preferences = getSharedPreferences("demo_preference",
            0);

    tv = (TextView) findViewById(R.id.tv);

    if(demo_preferences != null) {
        String usn = demo_preferences.getString("username", "");
        if (usn.isEmpty()) {
            tv.setText("Welcome");
        } else {
            tv.setText("Welcome " + usn);
        }
    }else{
        tv.setText("Welcome");
    }
}

@Override
protected void onResume() {
    super.onResume();

if(demo_preferences != null) {
        String usn = demo_preferences.getString("username", "");
        if (usn.isEmpty()) {
            tv.setText("Welcome");
        } else {
            tv.setText("Welcome " + usn);
        }
    }else{
        tv.setText("Welcome");
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.demo_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()) {
        case R.id.menu_settings:
            Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
                            startActivity(i);
            break;
        default:
            throw new RuntimeException("unknown menu selection");
    }

    return true;
}
}

2)PrefDemoActivity:-------

public class PrefDemoActivity extends AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FragmentManager mFragmentManager = getFragmentManager();
    FragmentTransaction mFragmentTransaction = mFragmentManager
            .beginTransaction();
    DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
    mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
    mFragmentTransaction.commit();

}

@Override
protected void onDestroy() {
    super.onDestroy();
        }
}

3)DemoEditPreferences:---------

public class DemoEditPreferences extends PreferenceFragment implements  SharedPreferences.OnSharedPreferenceChangeListener{

private SharedPreferences demo_preferences;
private int preferencesToEdit;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    demo_preferences = getActivity().getSharedPreferences("demo_preference",
            0);

    preferencesToEdit = R.xml.demo_preferences;
    String preferenceName = getResources().getString(R.string.pref_sensor_key);

    PreferenceManager preferenceManager = getPreferenceManager();
    preferenceManager.setSharedPreferencesName(preferenceName);
    preferenceManager.setSharedPreferencesMode(0);

    getActivity().setTitle("Demo Preferences");

    addPreferencesFromResource(preferencesToEdit);

    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initSummary(getPreferenceScreen().getPreference(i));
    }

}


@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if(findPreference(key) != null) {

        if(findPreference(key).getKey().equals("username")) {
            if(sharedPreferences.getString("username","").equals("")){
                setString("username","");
            }else{
                setString("username",sharedPreferences.getString("username","----"));
            }
        }

        updatePrefSummary(findPreference(key));
    }

}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        for (int i = 0; i < pCat.getPreferenceCount(); i++) {
            initSummary(pCat.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }
}

private void updatePrefSummary(Preference p) {

    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        p.setSummary(editTextPref.getText());
    }
}

public void setString(String preferenceName, String value)
{
    SharedPreferences.Editor editor = demo_preferences.edit();
    editor.putString(preferenceName, value);
    editor.apply();
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    view.setBackgroundColor(getResources().getColor(android.R.color.white));
    return view;
}

@Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

}

4)demo_activity.xml:------

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

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Welcome"
    android:id="@+id/tv"
    android:gravity="center"
    android:background="@android:color/holo_blue_light"/>

5)demo_menu.xml ---------------

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/menu_settings"
    android:title="Settings"
    android:titleCondensed="Settings"
    android:orderInCategory="1">
</item>

</menu>

6)demo_preferences:---------

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
    android:title="Demo">

    <EditTextPreference
        android:key="username"
        android:title="UserName"
        android:defaultValue="----"
        android:summary="----"
        android:selectAllOnFocus="true"
        android:singleLine="true">
    </EditTextPreference>

</PreferenceCategory>

</PreferenceScreen>

7)不要忘记将两种活动都添加到清单中。