如何在MainActivity()中访问片段元素?[英] how to access fragments elements in MainActivity()?

本文是小编为大家收集整理的关于如何在MainActivity()中访问片段元素?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在我的项目中,我想设置MainAttivity片段按钮的可见性.但是问题是,它给出了NullPoInterException().我还将ListBtn&GridBtn作为静态.我使用以下代码:

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

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

推荐答案

您无法从活动类访问片段视图,因为活动使用其自己的视图(例如:r.layout.activity_main).相反,您可以在相应的片段类中设置可见性,该类别将执行相同的工作.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.details, container, false);
        Button listBtn = (Button)view.findviewById(R.id.listBrn);
        Button gridBtn = (Button)view.findviewById(R.id.gridBrn);
        listBtn.setVisibility(View.GONE);
        gridBtn.setVisibility(View.GONE);
        return view;
    }

其他推荐答案

fragment onCreateView在活动方法onCreate后调用回调,因此我认为您尝试从中获得访问权限.该视图只有在调用onResumeFragments回调之后才能访问,您应该在片段中执行操作.

另一个提示是,您强烈不应该像您或通过通过静态引用 the worst. You should avoid such dependencies on fragments inner implementation. Instead of it, better is create some method like setInitialState (the name depends on your business logic) and just call it from activity.

So result code: In activity:

private FirstFragment fragment;

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //init fragment here
}

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    fragment.setInitialState();
}

In fragment:

//this will be called on fragment #onResume step, so views will be ready here.
public void setInitialState() {
   listBtn.setVisibility(View.GONE);
   gridBtn.setVisibility(View.GONE);
}

其他推荐答案

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);
}

And call it from activity:

fragment.hideButtons();