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

Posted

技术标签:

【中文标题】工具栏视图引用从对话框片段返回后变为空【英文标题】:Toolbar views reference becomes null after returned from dialog fragment 【发布时间】:2017-12-21 22:27:47 【问题描述】:

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

@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 和其他视图变为空。那么,当我从 dialogfragment 获取数据时,如何避免视图变为空

这是完整的片段代码

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

    


【问题讨论】:

请提供完整的活动代码 @RahulKhurana 请检查编辑后的代码 【参考方案1】:

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

点击按钮时调用对话框

`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://***.com/a/34527080/6527410

【讨论】:

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

Android,从其他片段返回的空列表视图

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

从拆分视图控制器中的详细视图进行回调委派后,主视图中的强属性属性变为空

Android Java:在 onCreateView() 中返回空视图的片段

cppcheck 空指针取消引用,但它实际上可以变为空

onDetach()不要求从一个片段移动到另一个片段