我正在使用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” 没问题,
但是,当您追逐片段类继承(androidx.fragment.app.Fragment)时,您将永远找不到该类继承 Context ,因此将“this” 作为Context传递是 Not Acceptable 。
实际上 getContext 和 requireContext 返回其宿主的上下文,因此您需要使用它们。
see有关“getContext”和“requireContext”之间的区别的更多信息。