Android获取活动片段的视图 [英] Android get view of fragment in activity
本文介绍了Android获取活动片段的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个活动,我们称它为 A
,它会像这样启动一个片段:
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();
我的 remoteFragment
看起来像这样:
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();
但是 okBtnMessageNotWorking
始终为空.
我的问题是如何从活动内部的片段中获取视图对象?
my question is how can I get the view objects from the fragment inside my activity?
推荐答案
在这里,您正在尝试从 layoutOnTopScrollview
查找视图.相反,您应该从展开视图中找到 okBtn
.请按如下所示更改代码:
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.
这篇关于Android获取活动片段的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文