How to get the sumary from preferences

丶灬走出姿态 提交于 2019-12-11 08:17:12

问题


One question: I have a EditTextPreference to let the user type in a default path for the app.

How can I manage that the new value is to be seen in the preferencefragment I use?

After the user clicked ok in the preference window to complete the new settings I want to write the new path as a summary below the title.

I have tried already experiencing with the onSharedPreferenceChanged but it did not work. I do not know how to get access to the edit field from the popup window where the users text is in.

Hope to find some help Andreas!

Edit: Here is the source code for the whole PreferenceFragment I used and modified with the suggestions of Rustam. Unfortunately it does not work.

package com.example.wbsettings;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;

public class PreferenceFrag extends PreferenceFragment 
implements SharedPreferences.OnSharedPreferenceChangeListener{

public static final String KEYVAL = "startpath"; 
SharedPreferences sp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    EditTextPreference prefUrl = (EditTextPreference) findPreference(KEYVAL);
    prefUrl.getEditText().setHint("default path");

    //>> Here the app crashed when I debug it
         ------------------------------------ 
    prefUrl.setSummary(sp.getString(KEYVAL, ""));

}//onCreate

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
    Preference pref = findPreference(key);
    if (pref instanceof EditTextPreference) {
        EditTextPreference etp = (EditTextPreference) pref;
        pref.setSummary(etp.getText());

    }
}//onSharedPreferenceChanged

}

What I also do not understand in your example: Where is the preferences to register with the OnSharedPreferenceChangeListener? I mean as of now I never reach the onSharedPreferenceChanged procedure because of the crash. But when I make the statement a comment and the app is running and finished I have never been stopped at the breakpoint I set within the onSharedPreferenceChanged procedure.

Another question: What is the best practice here to answer a comment if the answer becomes too long for another comment? I tried to open an answer to my own question. But a pop up informed me that this is not the way it should be. So what to do?

Regards Andreas!


回答1:


your menu_setting.xml :

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"

        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/menu_settings"
        android:icon="@android:drawable/ic_menu_preferences"/>

</menu>

your preference.xml :

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

    <EditTextPreference
        android:dialogTitle="Enter path"
        android:key="prefPath"
        android:summary=""
        android:title="Path Setting" />

</PreferenceScreen>

your PreferenceFrag should look like this :

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;

public class PreferenceFrag extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener{

public static final String KEYVAL = "prefPath"; 
SharedPreferences sp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preference);

    EditTextPreference prefPath = (EditTextPreference) findPreference(KEYVAL);
    prefPath.getEditText().setHint("sdcard/path");

    // Here the app crashed when I debug it

     SharedPreferences sp = getPreferenceScreen().getSharedPreferences();

         prefPath.setSummary(sp.getString(KEYVAL, ""));



}//onCreate


@Override
public void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    // Unregister the listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
}


public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
    Preference pref = findPreference(key);
    if (pref instanceof EditTextPreference) {
        EditTextPreference etp = (EditTextPreference) pref;
        pref.setSummary(etp.getText());

    }
}//onSharedPreferenceChanged

}

your PreferenceActivity :

import android.app.Activity;
import android.os.Bundle;

public class PreferenceActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PreferenceFrag()).commit();
 }

}

your MainActivity :

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview=(TextView)findViewById(R.id.textview);


    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.menu_settings:
            Intent i = new Intent(this, PreferenceActivity.class);
            startActivity(i);
            break;

        }

        return true;
    }



}

finally AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.preferencetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.preferencetest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.preferencetest.PreferenceActivity"/>
    </application>

</manifest>


来源:https://stackoverflow.com/questions/25865048/how-to-get-the-sumary-from-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!