怎么在viewpager中获取子fragment里面的控件

怎么在viewpager中获取子fragment里面的控件,第1张

想要 *** 控viewpager中获取焦点的fragment的控件,但是并没有getCurrentFragment 等类似的方法,但是提供了setPrimaryItem方法,但是这个实在adapter里面的,所有我们像个办法让他把当前的fragment从adapter中传出来,那么就要重写fragmentpageradapter

代码如下:

public class MyFragmentAdapter extends FragmentPagerAdapter {

public Fragment currentFragment;

public MyFragmentAdapter(FragmentManager fm, List<Fragment> list) {

super(fm);

thislist=list;

}

@Override

public void setPrimaryItem(ViewGroup container, int position, Object object) {

thiscurrentFragment= (Fragment) object;

supersetPrimaryItem(container, position, object);

}

@Override

public Fragment getItem(int position) {

return 。。。;

}

@Override

public int getCount() {

return。。。;

}

}

123456789101112131415161718192021222324252627

这样我们就可以通过外部调用currentFragment来获取当前fragment,

如:

((MyFragmentAdapter)viewPagergetAdapter())currentFragment

然后强转成你需要的fragment就可以啦。

调用方法的时候只要,fragmentgetView()finViewById();

比如:

MyFragment mf= (MyFragment ) ((MyFragmentAdapter)viewPagergetAdapter())currentFragment;

//找到控件

ScrollView scrollview= (ScrollView) mfgetView()findViewById(Ridtuijian_scrollview);

svgselectAll("place-label")

attr("x", function(d) { return dgeometrycoordinates[0] > -1 6 : -6; })

style("text-anchor", function(d) { return dgeometrycoordinates[0] > -1 "start" : "end"; })

一、使用Fragment获取控件Id

我是在MainActivity中通过Fragment的事务管理把各个fragment添加到MainActivity中的,但是MainActivity中并没有很多控件,控件大都在各个fragment的布局里面,所以如何在fragmen中获取控件Id是一件非常重要的事!话不多说直接上代码!

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View messageLayout=inflaterinflate(Rlayoutmessage_layout,container,false); inspect= (TextView) messageLayoutfindViewById(Ridinspect); inspectsetOnClickListener(new ViewOnClickListener() {

在OncreatView方法中,先是通过View方法把布局加载到fragmnet中,然后在使用加载的布局中的findViewById的方法找到控件,这和之前的用法是不一样的,之前是直接findViewById。

二、如何在fragment中跳转Activity

话不多话,直接上代码!

Intent intent=new Intent(getActivity(),InspectActivityclass);startActivity(intent);

与平常跳转不同的地方在于这里是:

new Intent(getActivity(),InspectActivityclass);

以上就是关于怎么在viewpager中获取子fragment里面的控件全部的内容,包括:怎么在viewpager中获取子fragment里面的控件、如何获取ViewPager当前的Fragment、使用Fragment时如何获取控件Id以及如何跳转等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9610272.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-30
下一篇2023-04-30

发表评论

登录后才能评论

评论列表(0条)

    保存