2016-02-14 89 views
0

我想添加一个片段,然后在上述片段中查找一个视图,并向其中添加一个视图。不过,我不断收到此声明的NullPointerException如何在片段中查找视图?

FrameLayout container2 = (FrameLayout) fragment.getActivity().findViewById(R.id.content_frame); 

这是我的代码。有人能告诉我如何解决这个问题吗?谢谢

FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    Fragment fragment = new FragmentNavigationDrawer(); 
    ViewGroup decor = (ViewGroup) getActivity().getWindow().getDecorView(); 
    View child = decor.getChildAt(0); 
    decor.removeView(child); 
    fragmentTransaction.add(decor.getId(), fragment); 
    fragmentTransaction.commit(); 
    FrameLayout container2 = (FrameLayout) fragment.getActivity().findViewById(R.id.content_frame); 
    container2.addView(child); 
+0

为什么要从Fragment包含的Activity中做Fragment.getActivity? –

+0

这段代码在哪里?在活动中还是在片段中? – Elye

+0

使用片段的getView方法并在返回的视图上调用findViewById。 – marktani

回答

0

请参阅javadoc FragmentTransaction.commit()。它表示它将时间表更改为片段返回堆栈。它不会立即发生。它看起来像你期待片段及其视图立即可用。

另外,我真的很困惑,为什么你在装修视图中进行更改。通常你会在主机活动的布局中通过id调用一个视图,并在其中进行更改。

+0

我认为OP需要使用'FragmentTransaction.replace' –

1

只要使用吸气剂。设置你的片段的标记,以便以后可以访问它,然后呼叫getView()您的片段返回其根视图,或者使用一个getter访问特定View

public class MainActivity extends AppCompatActivity { 

    //In onCreate 
    if (getFragmentManager().findFragmentByTag(FragmentNavigationDrawer.TAG) == null) { 
     getFragmentManager() 
      .beginTransaction() 
      .add(android.R.id.content, new FragmentNavigationDrawer(), FragmentNavigationDrawer.TAG) 
      .commit(); 
    } 

    //Later, when you want to add said View: 
    FragmentNavigationDrawer frag = 
     (FragmentNavigationDrawer) getFragmentManager().findFragmentByTag(FragmentNavigationDrawer.TAG) 

    //Return the root view: 
    View fragRootView = frag.getView(); 

    //Return a specific view: 
    frag.getUpdatableViewGroup().addView(newViewToAdd): 

} 

为了您的片段:

public class FragmentNavigationDrawer extends Fragment { 

    public static final String TAG = FragmentNavigationDrawer.class.getSimpleName(); 

    FrameLayout updatableViewGroup; 

    //Can do this inside onCreateView() whilst inflating your Fragment's Views 
    //That's up to you. 
    @Override 
    public void onViewCreated (View view, Bundle savedInstanceState) { 

     updateableViewGroup = view.findViewById(R.id.updateable_view_group); 

    } 

    public FrameLayout getUpdatableViewGroup() { 
     return updateableViewGroup; 
    } 

成为自觉的ActivityFragment生命周期。但是,并注意不要试图访问片段的意见,直到他们完成了膨胀 - 你ActivityonStart()以后应该没问题。