从对话框片段返回后,工具栏视图引用变为null

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从对话框片段返回后,工具栏视图引用变为null相关的知识,希望对你有一定的参考价值。

片段我有自定义工具栏,其中包含搜索视图,textview和按钮。

@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.nearby_friends_menu, menu);

    MenuItem item = menu.findItem(R.id.search_PTL);
    //searchView=new SearchView(((Navigation_Drawer)getActivity()).getSupportActionBar().getThemedContext());
    searchView = new SearchView(getActivity());


    MenuItemCompat.setActionView(item, searchView);
    Button voiceSearch = new Button(getActivity());
    LinearLayout.LayoutParams navButtonsParams = new LinearLayout.LayoutParams(toolbar.getHeight() * 2 / 3, toolbar.getHeight() * 2 / 3);
    voiceSearch.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_access_time_black_24dp));
    ((LinearLayout) searchView.getChildAt(0)).addView(voiceSearch, navButtonsParams);
    ((LinearLayout) searchView.getChildAt(0)).setGravity(Gravity.CENTER_VERTICAL);
    voiceSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Bundle bundle = new Bundle();
            bundle.putString("Calling", TAG);
            datepicker.setArguments(bundle);
            datepicker.show(getFragmentManager(), TAG);
        }
    });

    searchView.setQueryHint("Search");

    searchView.clearFocus(); // This is use for close the keyboard
    return true;
}

点击按钮,我在dialogfragment中打开一个日历,它将数据返回到片段,在logcat中成功打印。

public void searchItem(String query) {
    Log.d(TAG, "Query " + query + " " + searchView + " " + activityTitle + " " + switchButton); // All these views becomes null when get data here.
    if (searchView != null) {
        Log.d(TAG, "Search View Is Not Null");
        searchView.setQuery(query, false);
    } else {
        Log.d(TAG, "Search View Is NULL");
    }
}

我试图在这里将日期设置为searchview,但searchview和其他视图变为null。那么当我从dialogfragment获取数据时,如何避免视图变为null

这是完整的片段代码

public class ItemList extends Fragment {

    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    RecyclerView.LayoutManager layoutManager;
    onResultReceived listener,onRefresh_Interface;

    ImageView appLogo;
    TextView activityTitle;
    Switch switchButton;
    SearchView searchView;
    Toolbar toolbar;
    public static final String TAG="===Item List===";
    DialogFragment datepicker;

    public FriendsList() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG,"On Start Calling");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"ON CREATE CALLING ");

       }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view=inflater.inflate(R.layout.activity_item_list,container,false);
        recyclerView= (RecyclerView) view.findViewById(R.id.RecyclerViewForItemList);


                    adapter=new RecyclerFriendListAdapter(getActivity(),items);
                    layoutManager=new LinearLayoutManager(getActivity());
                    recyclerView.setLayoutManager(layoutManager);
                    recyclerView.setHasFixedSize(true);
                    recyclerView.setAdapter(adapter);


         //Setting Toolbar For Current Fragment
        toolbar= (Toolbar) getActivity().findViewById(R.id.Navigation_Drawer_toolbar);
        appLogo= (ImageView) toolbar.findViewById(R.id.appLogo);
        activityTitle= (TextView) toolbar.findViewById(R.id.activityTitle);
        ImageButton done= (ImageButton) toolbar.findViewById(R.id.doneButton);
        done.setVisibility(View.GONE);


        appLogo.setImageResource(R.drawable.invent_x);
        activityTitle.setText("Fav Items");
        setHasOptionsMenu(true);
        datepicker=new SelectDateFragment();
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            userData= (UserData) getActivity();
        }
        catch (ClassCastException e){
            throw new ClassCastException(getActivity().toString()+" Must Implement Interface");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"On Resume Calling");
      //  getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.nearby_friends_menu,menu);

        final MenuItem switchItem=menu.findItem(R.id.toggle_button);
        switchButton=new Switch(getActivity());
        switchButton=switchItem.getActionView().findViewById(R.id.Switch_screen);
        switchButton.setChecked(true);
        MenuItemCompat.setActionView(switchItem,switchButton);

        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    Log.d(TAG,"Location Button Is Checked");

                }
                else {

                    Log.d(TAG,"Location Button Is UnChecked");

                }

            }
        });
        MenuItem item=menu.findItem(R.id.search_PTL);
        //searchView=new SearchView(((Navigation_Drawer)getActivity()).getSupportActionBar().getThemedContext());
        searchView=new SearchView(getActivity());


        MenuItemCompat.setActionView(item,searchView);
        Button voiceSearch=new Button(getActivity());
        LinearLayout.LayoutParams navButtonsParams = new LinearLayout.LayoutParams(toolbar.getHeight() * 2 / 3, toolbar.getHeight() * 2 / 3);
        voiceSearch.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_access_time_black_24dp));
        ((LinearLayout)searchView.getChildAt(0)).addView(voiceSearch,navButtonsParams);
        ((LinearLayout)searchView.getChildAt(0)).setGravity(Gravity.CENTER_VERTICAL);
        voiceSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle=new Bundle();
                bundle.putString("Calling",TAG);
                datepicker.setArguments(bundle);
                datepicker.show(getFragmentManager(),TAG);
            }
        });

        searchView.setQueryHint("Search ");

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //switchButton.setVisibility(View.VISIBLE);
                Log.d(TAG,"Query Text Submit "+query);
                getActivity().invalidateOptionsMenu();

                searchView.clearFocus(); // This is use for close the keyboard
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return true;
            }
        });


        MenuItem.OnActionExpandListener expandListener=new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {
                Log.d(TAG,"On Menu Expand");
                switchItem.setVisible(false);
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                Log.d(TAG,"On Menu Collapse");
               // getActivity().invalidateOptionsMenu();
                return true;
            }
        };
        item.setOnActionExpandListener(expandListener);



    }
    public void searchUser(String query){
        Log.d(TAG,"Query "+query+ " "+searchView+" "+activityTitle+" "+switchButton);// THESE VIEWS ALSO BECOME NULL AFTER GETTING RESULT FROM DATE PICKER DIALOG
        dateQuery=query;
        if (searchView!=null){
            Log.d(TAG,"Search View Is Not Null");
            searchView.setQuery(query,false);
        }else {
            Log.d(TAG,"Search View Is NULL");
        }

    }

}
答案

而不是在片段中调用void方法获取结果从片段中的onActivityResult得到结果。

单击按钮时调用对话框

`dialog.setTargetFragment(this, 1);
dialog.show(fragmentManager, TAG);`

通过onActivityResult将值发送回片段

`Bundle bundle = new Bundle();
bundle.putString("MyKey", Value);
Intent intent = new Intent().putExtras(bundle);
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
dismiss();`

在Fragment中处理结果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
       String myValue = data.getExtras().getString("Mykey");
         Log.d(TAG,"My Value == "+myValue); //Handles your values here and views won't be null       

        }
    }

参考:https://stackoverflow.com/a/34527080/6527410

以上是关于从对话框片段返回后,工具栏视图引用变为null的主要内容,如果未能解决你的问题,请参考以下文章

从片段中的相机意图返回后屏幕变为白色

无法在对话框片段中的文本视图上设置文本

片段 null 必须是公共静态类才能从实例状态正确重新创建

从片段类中的对话框添加项目到recyclerview。

如何在屏幕方向更改时附加片段?

从 Settings Api 对话框打开位置后,getLastLocation() 返回 null