动态 add/remove 相同的 xml 视图

Dynamically add/remove the same xml view

我正在尝试在片段中添加和删除相同的 linearLayout 视图之间切换。每次我添加代码行:

    ((ViewGroup)indexLayout.getParent()).removeView(indexLayout)

我得到一个空指针异常,即使在尝试添加视图时也是如此...

OfflineFragment.java

private void displayIndex() {

     indexLayout = (LinearLayout)v.findViewById(R.id.side_index);

        List<String> indexList = new ArrayList<>(mapIndex.keySet());

        TextView textView;

        for (String index : indexList) {
            textView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.alphabet_indicator, null);
            textView.setText(index);
            textView.setOnClickListener(this);
            indexLayout.addView(textView);
        }
}

private void showDialog() {
    Dialog deleteDialog = new AlertDialog.Builder(getActivity()).setTitle("Warning:")
            .setMessage("Are you sure that you want to delete all offline contacts?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            //Delete cached data from internal storage and clear data structures
                            File dir = getActivity().getFilesDir();
                            File file = new File(dir, "cached.txt");
                            boolean deleted = file.delete();
                            System.out.println(deleted);
                            listView.setAdapter(null);
                            cachedSearch.clear();
                            l.clear();
                            mapIndex.clear();
                            sections = null;
                            names = null;
                           ((ViewGroup)indexLayout.getParent()).removeView(indexLayout)

                        }
                    }
            )
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }
            ).create();
    deleteDialog.show();
}

堆栈跟踪:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.OfflineFragment$override.displayIndex(OfflineFragment.java:122)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.OfflineFragment$override.refreshData(OfflineFragment.java:215)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.OfflineFragment$override.access$dispatch(OfflineFragment.java)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.OfflineFragment.refreshData(OfflineFragment.java:0)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.CarouselFragment.refreshData(CarouselFragment.java:215)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.MainActivity.update(MainActivity.java:120)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.SearchResultFragment.refreshData(SearchResultFragment.java:212)
                                                                                    at com.fil.uk.mobile.fidelitycontacts.Fragments.SearchResultFragment.onCreateView(SearchResultFragment.java:105)
                                                                                    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
                                                                                    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
                                                                                    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:758)
                                                                                    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1671)
                                                                                    at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:532)
                                                                                    at android.os.Handler.handleCallback(Handler.java:739)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:158)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

如果删除视图

 ((ViewGroup)indexLayout.getParent()).removeView(indexLayout)

你可以找回来!!如果你想使用它,你必须重新添加它

如果为空则尝试添加视图

private void displayIndex() {

     indexLayout = (LinearLayout)v.findViewById(R.id.side_index);

      if(indexLayout==null){
          LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(getContext().LAYOUT_INFLATER_SERVICE);
          View mView = inflater.inflate(R.layout.your_view_having_indexLayout , null, false);
          indexLayout =(LinearLayout)mView.findViewById(R.id.side_index);
      }  
        List<String> indexList = new ArrayList<>(mapIndex.keySet());

        TextView textView;

        for (String index : indexList) {
            textView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.alphabet_indicator, null);
            textView.setText(index);
            textView.setOnClickListener(this);
            indexLayout.addView(textView);
        }
}