与Kotlin共享Fragment中的首选项



我正在使用Kotlin在Android中制作一个计数器应用程序。我的代码在MainActivity中工作得很好,但当涉及到碎片时,它就不再工作了。

class HomeFragment : Fragment()
{
private lateinit var homeViewModel: HomeViewModel
@SuppressLint("SetTextI18n")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View?
{
/*homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)*/
val root = inflater.inflate(R.layout.fragment_home, container, false)
val textView: TextView = root.findViewById(R.id.text_home)
val button: Button = root.findViewById<Button>(R.id.button)
var nombre = PrefConfing.loadTotalFromPref(this)
button.setOnClickListener {
nombre++
textView.text = "vous l'avez fait $nombre fois"
PrefConfing.saveTotalTimes(applicationContext, nombre)
}
return root
}
}

这是我的Kotlin HomeFragment代码,还有我的Java代码:

public class PrefConfing {
private static final String TIMES = "com.example.alllerrr";
private static final String PREF_TOTAL_KEY = "pref_total_key";
public static void saveTotalTimes(Context context, int total) {
SharedPreferences pref = context.getSharedPreferences(TIMES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(PREF_TOTAL_KEY, total);
editor.apply();
}
public static int loadTotalFromPref(Context context){
SharedPreferences pref = context.getSharedPreferences(TIMES, Context.MODE_PRIVATE);
return pref.getInt(PREF_TOTAL_KEY, 0);
}
}

对于varnombre,我无法将其添加到上下文中,也不明白为什么。

您将知道原因:

如果您追求Activity类的继承,您会发现它继承了Context类,因此传递"这个">没有问题,但是当你追逐Fragment类继承(androidx.Fragment.app.Fragment(时,你永远不会发现类继承了Context,所以通过"这个">作为上下文。

实际上,getContextrequireContext返回其主机的上下文,因此需要使用它们。

requireContext:返回一个非null上下文,或在不可用时抛出异常。

getContext:返回可为null的Context。

查看更多关于";getContext"以及";requireContext";。

如果在行

var nombre = PrefConfing.loadTotalFromPref(this)

您得到的是:

Type mismatch.
Required: Context!
Found: HomeFragment

你必须这样做:

var nombre = PrefConfing.loadTotalFromPref(requireContext())

最新更新