Ton*_*van 0 java android sharedpreferences
我希望有人可以就如何在onViewCreated事件中定义的按钮的onclick事件中访问SharedPreferences给出一些指导.
我可以通过调用以下方法在onViewCreated事件中设置我的接口的值:
SharedPreferences prefs = this.getActivity().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)
并获得适当的值,但我在界面上有一个按钮来保存更改,我似乎无法从按钮的click事件中找到正确的方法来访问SharedPreferences:
Button btn = (Button)view.findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Log.d("test","here");
SharedPreferences prefs = this.getActivity().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
}
});
Run Code Online (Sandbox Code Playgroud)
这段代码显然不起作用,因为这里指的是视图,而getActivity在视图中不起作用.任何人都可以告诉我如何从这里访问活动,以便我可以访问SharedPreferences?
您好,欢迎来到StackOverflow.
你无法访问的原因SharedPreferences是因为this它不是片段:如果你仔细观察,你会发现你有2个嵌套的上下文,所以this它实际上是一个OnClickListener对象(在你的片段里面).
当您需要访问"父上下文"时,您可以这样做:
public class MyCoolFragment extends Fragment {
// here "this" is in fact your Fragment,
// so this.getActivity().getSharedPreferences() DOES exist
.
.
.
Button btn = (Button)findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
// "this" is NO LONGER your fragment, but the View.OnClickListener
// to access the PARENT CONTEXT you prepend the CLASS NAME:
// MyCoolFragment.this.getActivity().getSharedPreferences will work:
SharedPreferences prefs = MyCoolFragment.this.getActivity().getSharedPreferences()
"com.example.app", Context.MODE_PRIVATE);
}
});
Run Code Online (Sandbox Code Playgroud)
在Java中非常典型地具有深度嵌套的上下文,因此您必须告诉Java this您想要什么.
此外,请记住,您可以从任何视图轻松获取上下文.,所以在点击处理程序中你也可以这样做:
Button btn = (Button)view.findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Activity myActivity=(Activity)(v.getContext()); // all views have a reference to their context
SharedPreferences prefs =myActivity.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
}
});
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 !