如何从PagerAdapter类更改片段的textview

时间:2014-10-02 17:48:51

标签: java android android-fragments

我是新的。我在尝试使用pageradapter设置片段的文本时遇到问题。

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页

请帮帮我。非常感谢你

1 个答案:

答案 0 :(得分:1)

在你的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);
}