首页 > 解决方案 > 与 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我无法将其添加到上下文中,我不明白为什么。

标签: javaandroidkotlinsharedpreferences

解决方案


如果在行

var nombre = PrefConfing.loadTotalFromPref(this)

你得到:

Type mismatch.
Required: Context!
Found: HomeFragment

你必须这样做:

var nombre = PrefConfing.loadTotalFromPref(requireContext())

推荐阅读