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?
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.
FragmentManager fragMgr = getSupportFragmentManager(); FragmentTransaction fragTrans = fragMgr. beginTransaction(); MyFragment myFragment = new MyFragment(); //my custom fragment fragTrans. replace(android. R.
use getActivity() method. Which will return the enclosing activity for the fragment.
Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.
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()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With