java - 与 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
我无法将其添加到上下文中,我不明白为什么。
解决方案
如果在行
var nombre = PrefConfing.loadTotalFromPref(this)
你得到:
Type mismatch.
Required: Context!
Found: HomeFragment
你必须这样做:
var nombre = PrefConfing.loadTotalFromPref(requireContext())
推荐阅读
- bash - Shell / Bash:如何在命令行shell中未定义的函数上失败?
- outlook - 如何在 Outlook for Mac 中添加像 Cozi 这样的外部日历?
- sql-server - 如何自动创建另一个数据库的视图或同义词以及使用哪个
- vim - 如何记录 Vim 加密操作?
- ios - iPhoneXR 旋转后返回 rootview 控制器
- typescript - 方法装饰器 - 需要调用装饰器的类模块的完全限定路径
- delphi - 如何在delphi中为组件正确调用自定义组件编辑器表单
- pandas - 我需要在 python 2.7 中替换熊猫数据框列中的非 ASCII 字符
- php - 是否有更改 WordPress“重置密码表单”的钩子?
- sql - 返回更多值的子查询