Android get view of fragment in activity [duplicate]

徘徊边缘 提交于 2021-02-11 14:34:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!