我正在使用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);
}
}
对于var,nombre
我无法将其添加到上下文中,我也不明白为什么。
您会知道为什么:
如果您追踪Activity类的继承,您会发现它继承了Context类,因此传递“ this”没有问题,但是当您追踪Fragment类的继承(androidx.fragment.app.Fragment)时,您将永远找不到该类继承Context,因此不能将“ this”作为Context传递。
实际上,getContext和requireContext返回其宿主的上下文,因此您需要使用它们。
requireContext:返回一个非null的Context,或者在不可用时抛出异常。
getContext:返回可为空的上下文。
看到更多关于“的getContext”和“requireContext”之间的区别。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句