gpt4 book ai didi

java - 如何从 PagerAdapter 类更改 fragment 的 TextView

转载 作者:行者123 更新时间:2023-12-01 12:28:11 25 4
gpt4 key购买 nike

我是新人。尝试使用我的 pageradapter 设置 fragment 的文本时遇到问题。

Fragment 布局只有 1 个 TextView 。

public class Cau1 extends Fragment {

public TextView texview1;
public static String texthere = null;
public Cau1() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

View rootView = inflater.inflate(R.layout.fragment_, container, false);
texview1 = (TextView)rootView.findViewById(R.id.textView1);
texview1.setText(texthere);
return rootView;
}

我的适配器是:

public class MyPagerAdapter extends FragmentPagerAdapter {

public MyPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}

@Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if(arg0 == 0)
{
fragment = new Cau1();
Cau1.texthere = "This is page 1";

}
if(arg0 == 1)
{
fragment = new Cau1();
Cau1.texthere = "This is page 2";

}
if(arg0 == 2)
{
fragment = new Cau1();
Cau1.texthere = "This is page 3";

}
return fragment;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}

共有 3 页。其结果为:

首页:这是第 1 页

第二页:这是第 2 页

第三页:这是第 3 页

请帮助我。非常感谢

最佳答案

在您的 fragment 中有一个返回自身的静态方法

public class Cau1 extends Fragment {

public TextView texview1;
public int pageNumber;
public Cau1() {
// Required empty public constructor
}

static Cau1 newInstance(int pageNumber) {
Cau1 f = new Cau1();

Bundle args = new Bundle();
args.putInt("num", pageNumber);
f.setArguments(args);

return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt("num");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

View rootView = inflater.inflate(R.layout.fragment_, container, false);
texview1 = (TextView)rootView.findViewById(R.id.textView1);
texview1.setText("Page " + String.valueOf(pageNumber));
return rootView;
}

并将 FragmentPagerAdapter getItem() 替换为

@Override
public Fragment getItem(int arg0) {
return Cau1.newInstance(arg0+1);
}

关于java - 如何从 PagerAdapter 类更改 fragment 的 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com