I have a PreferenceFragmentCompat that I would like to use together with a corresponding ViewModel class. Is it doable?
The fragment is currently attached to an androidx AppCompatActivity and it works as intended. However, I would like to display the values of my Preferences under their summaries. Traditionally I would do all data manipulation inside the PreferenceFragment but I was made aware that google is suggesting the MVP architectural pattern.
This question might sound quite noob but I am still trying to get my head around the Jetpack after being away from android development for the past 3 years
The classes/files that I have are the following:
app_preference.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/your_account">
<Preference
app:key="email"
app:title="@string/title_email" />
</PreferenceCategory>
<PreferenceCategory
app:key="help"
app:title="@string/help_desk">
<Preference
app:key="feedback"
app:summary="@string/get_help_summary"
app:title="@string/get_help" />
</PreferenceCategory>
<Preference
app:key="terms"
app:title="@string/terms_of_service" />
<Preference
app:key="app_version"
app:title="@string/app_version_label" />
</PreferenceScreen>
MainActivity
package mypackage;
import android.os.Bundle;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import mypackage.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_settings, R.id.test_settings)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
}
}
Preference Fragment
package mypackage.ui.testFrag.settings;
import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat;
import mypackage.R;
public class TestSettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.app_preference, rootKey);
}
}