我想通过点击它来隐藏一个片段XML的按钮,因为它总是会被隐藏,直到通过共享首选项卸载应用程序。但我收到错误,' android.widget.button'的未知方法setVisibility和' btnsearch变量必须是最终用于本地课程' 。这是我的代码:
package com.niezwm.bododictionary.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import android.view.ViewGroup;
import android.widget.Button;
import android.content.Context;
import android.content.SharedPreferences;
import com.niezwm.bododictionary.R;
public class SearchFragment extends Fragment{
SharedPreferences sharedPreferences;
Button btnsearch;
public SearchFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_search, container,false);
Button btnsearch =(Button) rootView.findViewById(R.id.btnsearch);
SharedPreferences sharedPreferences =this.getActivity().getSharedPreferences("pref",0);
btnsearch.setVisiblity(sharedPreferences.getBoolean("visiblity",false));
btnsearch.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
if(
btnsearch.getVisibility()==View.INVISIBLE){
btnsearch.setVisibility(View.VISIBLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("visiblity",true)
.commit();
}
Toast.makeText(getActivity(), "search", Toast.LENGTH_LONG).show();
}
// end onClick
});
return rootView;
}
// end onCreateView
}
答案 0 :(得分:0)
如果您在匿名内部类中访问这两个变量,则必须使它们成为最终:
final Button btnsearch = (Button) rootView.findViewById(R.id.btnsearch);
final SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("pref", 0);
修改强>
setVisibility()
想要一个int,而不是布尔值。
boolean visibility = sharedPreferences.getBoolean("visiblity", false);
btnsearch.setVisibility(visibility ? View.VISIBLE : View.GONE);