本文介绍了如何访问MainActivity()中的fragment元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我想设置MainActivity中片段按钮的可见性.但是问题是,它给出了NullPointerException().我还列出了listBtn& gridBtn为静态.我使用下面的代码:

In my project, I want to set visibility of fragments buttons from MainActivity. But the problem is, it gives NullPointerException(). I also maked listBtn & gridBtn as static. I used below code :

 FirstFragment fragment = (FirstFragment)getSupportFragmentManager().findFragmentById(R.id.    <frameLayout Id>);

  main_page_fragment.listBtn.setVisibility(View.GONE);
  main_page_fragment.gridBtn.setVisibility(View.GONE);

推荐答案

如果您通过MainActivity动态添加片段,如下所示:

If you add your fragments dynamically from MainActivity like so:

YourFragment fragment = new YourFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, fragment, YOUR_TAG)
            .commit();

然后您可以在片段中定义方法,如下所示:

Then you can define method in your fragment like so:

public void hideButtons()
{
    yourBtn.setVisibility(View.GONE);
}

并从活动中调用它:

fragment.hideButtons();

这篇关于如何访问MainActivity()中的fragment元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 02:10