admin管理员组

文章数量:1122832

I am using

implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.preference:preference-ktx:1.2.1'

My preferences.xml is

<?xml version="1.0" encoding="utf-8"?>

<androidx.preference.PreferenceScreen xmlns:android="; xmlns:app=";\>

    <EditTextPreference
        android:key="edit_text_preference"
        android:title="Broadcast IP"
        app:useSimpleSummaryProvider="true"
        android:defaultValue="auto" />
    
    <Preference
        android:title="Factory reset"
        android:key="@string/myCoolButton"
        android:summary="Reset all settings"
        />

</androidx.preference.PreferenceScreen>

As you can see that I have used SimpleSummaryProvider in EditTextPreference so that user input is shown by default below "Broadcast IP"

In MainActivity.kt I create SettingsActivity.java when user clicks on three vertical dots at top right as follows


class MainActivity : AppCompatActivity() {

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.main_menu, menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.getItemId()) {
R.id.action_settings -\> {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
true
}
else -\> super.onOptionsItemSelected(item)
}
}

override fun onCreate(savedInstanceState: Bundle?) {
.
.
.
}

override fun onResume() {
super.onResume()
val sharedPreferences: SharedPreferences =
getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val username = sharedPreferences.getString("key changed", "no change")
if(username!=null)
Log.d("code-debug in onresume of main",username)
}

}

Here is my SettingsActivity.java

public class SettingsActivity extends AppCompatActivity {
SharedPreferences prefs;
SharedPreferences.OnSharedPreferenceChangeListener mylistener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
    
        getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                mit();
        prefs= PreferenceManager.getDefaultSharedPreferences(this);
        mylistener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
                // Implementation
                System.out.println("code-debug : key changed "+ key);
                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("key changed", key);
                editor.apply();
            }
        };
        prefs.registerOnSharedPreferenceChangeListener(mylistener);
    }

}

here is my SettingsFragment.kt

class SettingsFragment : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
    
        setPreferencesFromResource(R.xml.preferences,rootKey)
        val button: Preference? = findPreference(getString(R.string.myCoolButton))
        button!!.onPreferenceClickListener =
            Preference.OnPreferenceClickListener {
                Log.d("code-debug","you pressed reset all settings")
    
                    Log.d("code-debug","trying factory reset")
                    val newUsername="factoryreset"
                    val mysharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
                    with(mysharedPreferences.edit()) {
                        putString("edit_text_preference", newUsername)
                        apply()
                        // Apply the changes asynchronously
                    }
                true
            }
    }

}

My expectation is that on pressing factory reset button the Broadcast IP text should become "factoryreset" immediately.

Currently it does not . If I press back button the return to settings then I can see "factoryreset" which will be bad user experience .

I have tried to refresh fragment in button!!.onPreferenceClickListener using

val ft = parentFragmentManager.beginTransaction() 
ft.detach(this).attach(this)mit()

But no success.

I also tried

val usernamePreference: EditTextPreference? = findPreference("edit_text_preference")
usernamePreference?.let {
    it.summary = "Current username: JohnDoe"
Log.d("code-debug","did you see john doe")// Update the summary dynamically
}

before 'true' in button!!.onPreferenceClickListener

I get crash with log saying

    java.lang.IllegalStateException: Preference already has a SummaryProvider set.

Then , i thought of adding some other UI activity to factory reset button click . So, I added checkbox to preferences.xml

     <CheckBoxPreference
            android:key="check_box_preference"
            android:title="Check Box Preference"
            android:summary="An example of a CheckBoxPreference"
            android:defaultValue="true"/>

Now I added toggle checkbox code before true in button!!.onPreferenceClickListener of SettingsFragment.kt

    val togglecheckbox : CheckBoxPreference?
    =findPreference("check_box_preference")
                    togglecheckbox?.let {
                        val currcbstatus:Boolean = it.isChecked
                        it.isChecked = currcbstatus != true
                    }

I found that factory reset button press toggles checkbox as expected .

This confirms that issue is regarding updating EditTextPreference having useSimpleSummaryProvider .

本文标签: updating PreferenceScreen immediately on button press in androidStack Overflow