提问人:mobile developer 提问时间:12/6/2019 更新时间:12/6/2019 访问量:137
java.lang.NullPointerException:空对象引用上的 FloatingActionButton.setVisibility(int)'
java.lang.NullPointerException: FloatingActionButton.setVisibility(int)' on a null object reference
问:
我创建了一个活动,其中包含四个浮动按钮和一个片段,该片段调用活动的浮动按钮以使它们可见/不可见,但是当我从片段访问这些浮动按钮时,它会抛出空指针异常。
活动代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getInitialized();
fabSettings = (FloatingActionButton) this.findViewById(R.id.fabSetting);
fabStory = (FloatingActionButton) this.findViewById(R.id.fabStory);
fabImage = (FloatingActionButton) this.findViewById(R.id.fabImage);
fabVideo = (FloatingActionButton) this.findViewById(R.id.fabVideo);
}
片段代码:
@SuppressLint("RestrictedApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_community, container, false);
SessionManager sessionManager = new SessionManager(getActivity());
if(sessionManager.isLoggedIn()){
ActivityUser.fabSettings.setVisibility(View.VISIBLE);
ActivityUser.laySearchCode.setVisibility(View.VISIBLE);
ActivityUser.bottomLayout.setVisibility(View.VISIBLE);
tvCreateCommunity.setVisibility(View.VISIBLE);
}else{
MainActivity.fabSettings.setVisibility(View.VISIBLE);
MainActivity.bottomLayout.setVisibility(View.VISIBLE);
MainActivity.laySearchCode.setVisibility(View.VISIBLE);
((MainActivity) getActivity()).getSupportActionBar().setTitle("");
tvCreateCommunity.setVisibility(View.GONE);
}
}
请帮忙
答:
0赞
X-Byte Technolabs pvt. ltd.
12/6/2019
#1
使用此代码
片段:
public class Fragment extends Fragment {
public interface onHideEventListener {
public void hideEvent(boolean isVisible);
}
onHideEventListener hideEventListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
hideEventListener = (onHideEventListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onHideEventListener");
}
}
final String LOG_TAG = "myLogs";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment2, null);
SessionManager sessionManager = new SessionManager(getActivity());
if(sessionManager.isLoggedIn()){
hideEventListener.hideEvent(false);
}else{
hideEventListener.hideEvent(true);
}
return v;
}
}
活动:
public class MainActivity extends Activity implements onSomeEventListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void hideEvent(boolean isVisible) {
fabSettings.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
laySearchCode.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
bottomLayout.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
}
}
评论