通过ActionBar向片段添加视图

时间:2015-04-26 17:55:28

标签: android android-fragments view android-actionbar

我有一个带有Actionbar和Fragment的NavigationDrawer。 My Fragment有一个带有RelativeView的ScrollView我试图将其他视图添加到这个RelativeView。我最终在addView()方法中使用NullExceptionPointer,这意味着我的一个对象为null,但我无法弄明白 - 尽管如果我在Fragment类中调用addView()它会起作用。我的问题是为什么它是这样的。为什么我最终会选择NPE。我只是想了解我做错了什么。

进一步研究发现mContainer为null。但我膨胀fragment_main然后为什么它仍然是null?

我简化的MainActivity:

public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

   private ViewGroup mContainer;

@Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.getLayoutInflater.inflate(R.layout.fragment_main);
    mContainer = (ViewGroup) findViewById(R.id.main_container);
}

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:

            NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
            return true;

        case R.id.action_add_item:


            addItem(); **// NullPointerException**
            return true;
    }

    return super.onOptionsItemSelected(item);
}

 public void addItem() {    //method responsible for NPE  


    LayoutInflater layoutInflater = this.getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.ingredient, null);

    final ViewGroup newView =(ViewGroup) layoutInflater.inflate(R.layout.list_example,mContainer,false);


    mContainer.addView(newView, 0);
}

    public static class PlaceholderFragment extends Fragment {


    private View nicView;




       public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_main, container, final ViewGroup mainContainer = (ViewGroup) rootView.findViewById(R.id.main_container);
        final View nicView = View.inflate(getActivity(),R.layout.nicotine, null);
        mainContainer.addView(nicView, 0);

     return rootView;
    }

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:0)

你的堆栈跟踪显示不应该是NPE发生吗?

布局inflater是否可能为空?

他们通过

来规范我的inflater
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);