Android 如何从活动调用片段函数?
我想在SettingsFragment from Main活动中调用LoadFromSharedReferences()函数。如何在不将ConstraintLayout更改为FragmentLayout的情况下实现这一点?请记住,我是新的android和碎片! 设置片段XML:Android 如何从活动调用片段函数?,android,android-fragments,android-fragmentactivity,Android,Android Fragments,Android Fragmentactivity,我想在SettingsFragment from Main活动中调用LoadFromSharedReferences()函数。如何在不将ConstraintLayout更改为FragmentLayout的情况下实现这一点?请记住,我是新的android和碎片! 设置片段XML: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.Constrai
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SettingsFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@+id/textView6"
android:layout_width="113dp"
android:layout_height="49dp"
android:layout_gravity="top"
android:layout_marginStart="131dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="137dp"
android:text="@string/settings"
android:textSize="28sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/tvDarkSide"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvDarkSide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:text="@string/light_dark_mode"
android:textColor="#F10000"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/switchMode"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/switchMode" />
<Switch
android:id="@+id/switchMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="110dp"
android:layout_marginEnd="23dp"
android:text="Switch"
android:textSize="18sp"
android:checked="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
SettingsFragmentclas:
public class SettingsFragment extends Fragment {
public SettingsFragment() {
// Required empty public constructor
}
public static final String SAVE_SWITCH = "saveSwitch";
public static final String IS_CHECKED = "isChecked";
Switch switchTheme;
SharedPreferences sharedPreferences;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_settings, container, false)
switchTheme = (Switch) view.findViewById(R.id.switchMode);
sharedPreferences = getActivity().getApplicationContext()
.getSharedPreferences( SAVE_SWITCH , Context.MODE_PRIVATE);
loadFromSharedPreferences();
switchTheme.setChecked(sharedPreferences.getBoolean(IS_CHECKED,false));
switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
SharedPreferences.Editor editor = sharedPreferences.edit();
//Scriere in fis SharedPreferences
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
editor.putBoolean(IS_CHECKED,true);
switchTheme.setChecked(true);
editor.apply();
((MainActivity) getActivity()).ToggleTheme(isChecked);
}
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
editor.putBoolean(IS_CHECKED, false);
switchTheme.setChecked(false);
editor.apply();
((MainActivity) getActivity()).ToggleTheme(isChecked);
}
}
});
return view;
}
//Citire din fis SharedPreferences
private void loadFromSharedPreferences() {
boolean ischecked = sharedPreferences.getBoolean(IS_CHECKED, false);
switchTheme.setChecked(ischecked);
((MainActivity) getActivity()).ToggleTheme(ischecked);
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//loadFromSharedPreferences()
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.AppThemeDark);
} else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_main);
final DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
drawerLayout.openDrawer(GravityCompat.START);
}
});
NavigationView navigationView = findViewById(R.id.navigationView);
navigationView.setItemIconTintList(null);
NavController navController = Navigation.findNavController(this, R.id.navHostFragment);
NavigationUI.setupWithNavController(navigationView, navController);
final TextView textTitle = findViewById(R.id.textTitle);
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
textTitle.setText(destination.getLabel());
}
});
}
//AppCompatDelegate.setDefaultNightMode will cause your activities to reload automatically
public void ToggleTheme( boolean isChecked ){
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
设置碎片类别:
公共类设置片段扩展片段{
公共设置片段(){
//必需的空公共构造函数
}
公共静态最终字符串SAVE_SWITCH=“saveSwitch”;
公共静态最终字符串为\u CHECKED=“isChecked”;
切换主题;
SharedReferences SharedReferences;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
视图=充气机。充气(R.layout.fragment\u设置,容器,错误)
switchTheme=(Switch)view.findViewById(R.id.switchMode);
SharedReferences=getActivity().getApplicationContext()
.getSharedReferences(SAVE\u开关、Context.MODE\u PRIVATE);
LoadFromSharedReferences();
setChecked(sharedPreferences.getBoolean(IS_CHECKED,false));
setOnCheckedChangeListener(新的CompoundButton.OnCheckedChangeListener(){
SharedReferences.Editor=SharedReferences.edit();
//fis SharedReferences中的Scriere
@凌驾
检查更改后的公共无效(复合按钮视图,布尔值已检查){
如果(已检查){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE\u NIGHT\u YES);
编辑器.putBoolean(是否选中,true);
switchTheme.setChecked(true);
editor.apply();
((MainActivity)getActivity())。切换主题(已选中);
}
否则{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE\u NIGHT\u NO);
编辑器.putBoolean(是否选中,false);
switchTheme.setChecked(false);
editor.apply();
((MainActivity)getActivity())。切换主题(已选中);
}
}
});
返回视图;
}
//Citire din fis股份参考
私有void loadfromSharedReferences(){
boolean ischecked=SharedReferences.getBoolean(是否选中,false);
switchTheme.setChecked(ischecked);
((MainActivity)getActivity())。切换主题(已选中);
}
}
主要活动类别:
公共类MainActivity扩展了AppCompatActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//LoadFromSharedReferences()
如果(AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE\u NIGHT\u YES){
setTheme(R.style.AppThemeDark);
}否则{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_main);
最终抽屉布局抽屉布局=findViewById(R.id.抽屉布局);
findviewbyd(R.id.imageMenu).setOnClickListener(newview.OnClickListener()){
@凌驾
公共void onClick(视图){
抽屉布局。打开抽屉(重力compat.START);
}
});
NavigationView NavigationView=findViewById(R.id.NavigationView);
navigationView.SetItemIContentList(空);
NavController NavController=Navigation.findNavController(this,R.id.navHostFragment);
NavigationUI.setupWithNavController(navigationView,navController);
最终文本视图文本标题=findViewById(R.id.textTitle);
navController.addOnDestinationChangedListener(新的navController.OnDestinationChangedListener(){
@凌驾
公共无效onDestinationChanged(@NonNull NavController控制器、@NonNull NavDestination目标、@Nullable捆绑参数){
textitle.setText(destination.getLabel());
}
});
}
//AppCompatDelegate.setDefaultNightMode将导致活动自动重新加载
公共无效切换主题(布尔值已选中){
如果(已检查){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE\u NIGHT\u YES);
}
否则{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE\u NIGHT\u NO);
}
}
}
从活动调用片段函数非常简单。
(您需要在fragmet的xml文件中向其添加一个id)
从活动调用片段函数非常容易。 (您需要在fragmet的xml文件中向其添加一个id)
我尝试了您的解决方案,但现在它给了我一个错误“尝试调用空对象引用错误上的虚拟方法'void setingsFragment.loadFromSharedReferences()”android“我尝试了您的解决方案,但现在它给了我一个错误”尝试调用虚拟方法'void setingsFragment.loadFromSharedReferences())“在空对象引用错误上”
FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.your_fragment_id);
fragment.loadFromSharedPreferences();
FragmentManager manager = getSupportFragmentManager();
//Try to get instance of fragment from fragment Manager
Fragment fragment = manager.findFragmentById(R.id.your_fragment_id);
// create new instance of fragment if fragment not exist in fragment manager
if(fragment == null) {
fragment = new SettingsFragment();
}
fragment.loadFromSharedPreferences();