Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get view of Fragment from FragmentActivity

I have a FragmentActivity where I add a Fragment. Depending on some situation, I want to access Buttons from that fragment's layout and change click listeners of them.

What I do is:

View view = myFragment.getView(); Button myButton = (Button) view.findViewById(R.id.my_button); myButton.setOnClickListener(new MyClickListener()); 

But the view variable is always null.

How can I get the view of the activity?

like image 453
Drastamat Avatar asked Jun 10 '13 11:06

Drastamat


People also ask

How do I get the currently displayed fragment?

To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.

How do I get the current fragment from supportFragmentManager?

FragmentManager fragMgr = getSupportFragmentManager(); FragmentTransaction fragTrans = fragMgr. beginTransaction(); MyFragment myFragment = new MyFragment(); //my custom fragment fragTrans. replace(android. R.

How do you get FragmentActivity in a fragment?

use getActivity() method. Which will return the enclosing activity for the fragment.

Can you use findViewById in fragment?

Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.


1 Answers

If you want to access your component and set some data, I suggest you to make a method inside the fragment like this:

import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button;  public class DetailFragment extends Fragment {      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,             Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.details, container, false);         return view;     }       public void setSettings(){         Button button = (Button) getView().findViewById(R.id.my_button);         button.setOnClickListener(new MyClickListener());     } } 
like image 129
Jarvis Avatar answered Oct 05 '22 17:10

Jarvis