-4

How to Show activity element or view in it's fragment and also access from fragment without move from fragment to activity and also tell vice-versa of this scenario.

Here is My Problem:-

I am using Search Edit Box in Activity and I want to use this Search Box into my fragment but i don't want make any search box in fragment, I just want to show this Activity Search Box in Fragment When Ever User type in search box then by using textWatcher track the text and show the result of search box in fragment not in Activity. Below is the image of UI that i want make it. Check the Image for more details

Praveen Kumar
  • 277
  • 2
  • 12

1 Answers1

1

You can access activity elements and methods from fragment this way:

Activity template

public class ActivityMain extends AppCompatActivity {

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

   public void updateView(){
       // update your views & vars here
   }
}

Fragment template

public class BlankFragment extends Fragment {

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        
       return inflater.inflate(R.layout.fragment_blank, container, false);
   }
}

public void updateActivityView(){
    if (getActivity() != null){
        ((ActivityMain) getActivity()).updateView();
    }
}

For vice versa you can access fragment items from activity this way:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name(); 

Where R.id.example_fragment is most likely the FrameLayout id inside your xml layout

Hamid Reza
  • 624
  • 7
  • 23