问题
I have an activity, let's call it A
, and it launches a fragment like so:
remoteFragment = new RemoteFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout_remote_activity, remoteFragment)
.commit();
my remoteFragment
looks something like this:
public Button okBtn;
public RemoteFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_remote, container, false);
okBtn= view.findViewById(R.id.okBtn);
return view;
}
public RemoteLayoutView getOkBtn() {
return okBtn;
}
and in my activity I am trying to get it like so:
Button okBtnMessageNotWorking = remoteFragment.getOkBtn();
but okBtnMessageNotWorking
is always null.
my question is how can I get the view objects from the fragment inside my activity?
回答1:
Here, you are trying to find the view from layoutOnTopScrollview
. Instead you should find the okBtn
from inflated view. Please change code as below:
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_remote, container, false);
okBtn= view.findViewById(R.id.okBtn);
return view;
}
Also, make sure that you are calling this method once the fragment is created.
来源:https://stackoverflow.com/questions/62406558/android-get-view-of-fragment-in-activity