How To Access Fragments Elements In Mainactivity()?
Solution 1:
You cannot access to your fragment view from Activity class because activity uses its own view (ex: R.layout.activity_main). Rather you can set visibility in your corresponding fragment class which will do the same job.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Viewview= inflater.inflate(R.layout.details, container, false);
ButtonlistBtn= (Button)view.findviewById(R.id.listBrn);
ButtongridBtn= (Button)view.findviewById(R.id.gridBrn);
listBtn.setVisibility(View.GONE);
gridBtn.setVisibility(View.GONE);
return view;
}
Solution 2:
Fragment onCreateView
callback is called after onCreate
method of activity, so i think you have tried to get access from it. That views will be accessible only after onResumeFragments
callback is called, you should perform your actions with fragments there.
Another tip is that you strongly should not call views of fragments directly like you did or via static reference to views that's the worst. You should avoid such dependencies on fragments inner implementation. Instead of it, better is create some method like setInitialState
(the name depends on your business logic) and just call it from activity.
So result code: In activity:
privateFirstFragment fragment;
protectedvoidonCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init fragment here
}
@OverrideprotectedvoidonResumeFragments() {
super.onResumeFragments();
fragment.setInitialState();
}
In fragment:
//this will be called on fragment #onResume step, so views will be ready here.publicvoidsetInitialState() {
listBtn.setVisibility(View.GONE);
gridBtn.setVisibility(View.GONE);
}
Solution 3:
If you add your fragments dynamically from MainActivity like so:
YourFragmentfragment=newYourFragment();
FragmentManagerfragmentManager= getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, fragment, YOUR_TAG)
.commit();
Then you can define method in your fragment like so:
publicvoidhideButtons()
{
yourBtn.setVisibility(View.GONE);
}
And call it from activity:
fragment.hideButtons();
Solution 4:
I struggle with this for several hours and I found a much simpler solution.
Inside the fragment, simply make a public function (outside the on create view method) with the behavior that you want.
funhideElement() {
binding.button.visibility = View.GONE
}
And then in main activity access to the fragment and call the function.
binding.bottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId){
R.id.someFragment -> someFragment.hideElement()
}
}
Post a Comment for "How To Access Fragments Elements In Mainactivity()?"