我正在使用Viewpager显示一些editext
在图片中,红色矩形是我的片段,蓝色矩形是我的活动
在我的活动中,我像这样实现片段
myAtivity
@Override
protected void onCreate(Bundle savedInstanceState) {
...
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
CardFragmentPagerAdapter pagerAdapter = new CardFragmentPagerAdapter(getSupportFragmentManager(), dpToPixels(2, this));
ShadowTransformer fragmentCardShadowTransformer = new ShadowTransformer(viewPager, pagerAdapter);
fragmentCardShadowTransformer.enableScaling(true);
viewPager.setAdapter(pagerAdapter);
viewPager.setPageTransformer(false, fragmentCardShadowTransformer);
viewPager.setOffscreenPageLimit(3);
...
CardFragmentPagerAdapter
public class CardFragmentPagerAdapter extends FragmentStatePagerAdapter implements CardAdapter {
private List<CardFragment> fragments;
private float baseElevation;
public CardFragmentPagerAdapter(FragmentManager fm, float baseElevation) {
super(fm);
fragments = new ArrayList<>();
this.baseElevation = baseElevation;
for(int i = 0; i< 3; i++){
addCardFragment(new CardFragment());
}
}
@Override
public float getBaseElevation() {
return baseElevation;
}
@Override
public CardView getCardViewAt(int position) {
return fragments.get(position).getCardView();
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public Fragment getItem(int position) {
return CardFragment.getInstance(position);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object fragment = super.instantiateItem(container, position);
fragments.set(position, (CardFragment) fragment);
return fragment;
}
public void addCardFragment(CardFragment fragment) {
fragments.add(fragment);
}
}
所有我在CardFragment
标准片段中使用的编辑文本
我的问题是如何在我的活动中使用片段编辑文本的数据
我使用这个教学课程来执行此观看页面https://rubensousa.github.io/2016/08/viewpagercards
答案 0 :(得分:0)
您可以使用接口回调来实现:
添加此新界面:
interface OnItemClickListener {
void onItemClicked(int position);
}
在您的片段中:
private OnItemClickListener listener;
此外,添加一个函数来设置此侦听器:
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
最后在您的活动中:
pagerAdapter.setOnItemClickListener(this);
在“活动”上实现界面:
class MyActivity extends --- implements OnItemClickListener
覆盖其方法:
void onItemClicked(int position) {
//do what you want in your Activity
}
最后一步:
在为ViewPager实例化Fragment时,将Activity设置为Fragment的侦听器:
//this == getActivity()
MyFragment.newInstance(this)