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?
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());
}
}
try this:
public class YourFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_fragment, null);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
if(view != null) {
view.findViewById(R.id.my_button).setOnClickListener(new MyClickListener());
}
}
}
this code must works fine.
I hope, this will help you.
To set OnClickListeners in fragments, override onViewCreated
in your fragment class.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
//or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
I was trying to set a timertask to automatically reload a webview in a fragment and this method was the only thing that worked for me. My project is on github.
Source: this answer
When you initialize your button inside a class that extends Fragment
it's better to do it inside the onViewCreated()
method. This will guarantee that the view already exists.
Simply Use the getRootView()
method to get the data of your fragment in Activity.
//below block of code write in activity.
EditText et = (EditText) v.getRootView().findViewById(R.id.name);
Log.d("Name", et.getText().toString());
name is the field of fragment.