我希望当用户点击后退按钮时,relativelayout消失
在我的onCreateView()方法中,我正在实例化一个RelativeLatout视图:
VerbFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_verbs,container, false);
relativeLayout = (RelativeLayout)rootView.findViewById(R.id.rlListVerb);
relativeLayout.setVisibility(View.GONE);
我想从其他方法访问亲戚(backButtonWasPressed())
public void backButtonWasPressed() {
Log.d("hi ", "back is pressed");
if (!visible) {
relativeLayout.setVisibility(View.GONE);
} else relativeLayout.setVisibility(View.VISIBLE);
}
当按下后退按钮时,在MainActivity2中调用此方法:
MainActivity2
@Override
public void onBackPressed() {
VerbFragment fragment = new VerbFragment();
fragment.backButtonWasPressed();
}
但是我收到了这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setVisibility(int)' on a null object reference
at Fragments.VerbFragment.backButtonWasPressed(VerbFragment.java:258)
at Activitys.MainActivity2.onBackPressed(MainActivity2.java:136)
答案 0 :(得分:0)
:
relativeLayout.setId(IntValueHere);
您可以创建一个全局relativelayout var:
private RelativeLayout myLayout;
现在,在设置id:
后,将创建的RelativeLayout分配给myLayoutmyLayout = relativeLayout;
最后在你的backButtonWasPressed(){}你可以访问myLayout引用,它应该没问题。
另外,你可以给backButtonWasPressed一个relativeLayout参数并传递你的" relativeLayout"它。
为backButtonWasPressed提供RelativeLayout的参数
public void backButtonWasPressed(RelativeLayout layoutToTake){
if(!visible){
layoutToTake.setVisibility(View.GONE);
}
}
答案 1 :(得分:0)
似乎发生这种情况是因为backButtonWasPressed()
来自MainActivity2
,而不是来自VerbFragment
。这种情况relativeLayout
变量可以是null
。您可以通过检查VerbFragment
的可见性来避免这种情况,例如:
public void backButtonWasPressed() {
Log.d("hi ", "back is pressed");
if (getView() == null || !isMenuVisible()) {
return;
}
if (!visible) {
relativeLayout.setVisibility(View.GONE);
} else relativeLayout.setVisibility(View.GONE);
}
答案 2 :(得分:0)
当片段添加到Activity时,它有一个标记参数。
fragmentTransaction.add(R.id.container, fragment, tag);
现在,在Activity的backButtonWasPressed()方法中,您可以使用标记找到该片段,如果它不为null,则调用片段的 backButtonWasPressed()。 / p>
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment verbFragment = fragmentManager.findFragmentByTag(fragmentTag);
if(verbFragment !=null && verbFragment .isVisible()){
verbFragment .backButtonWasPressed();
}