android.support.v4.view.ViewPager无法强制转换为android.widget.TextView

时间:2016-07-04 05:15:04

标签: java android

    public class PageFragment extends android.support.v4.app.Fragment{
    public static final String ARG_PAGE = "arg_page";
    private int mPage;//页码
    public static PageFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);//向Bundle对象中添加键值对
        PageFragment fragment = new PageFragment();
        fragment.setArguments(args);//碎片中含有存储了键值对的bundle对象,为碎片提供了一个
        //相当于结构参数,伴随碎片创造和摧毁
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);//获得结构参数
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container);//布局转换为视图控件
        TextView textView = (TextView) view;//向下转型
        textView.setText("Fragment #" + mPage);
        return view;
    }
}

这是我的mainActivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //连接页面和碎片页面适配器,使他能展示页面
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);


    viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
                MainActivity.this));
    //将试图页给予标签布局
    TabLayout tabLayout = (TabLayout) findViewById(R.id.Sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);//将两者连接起来

}

我正在向http://guides.codepath.com/android/Google-Play-Style-Tabs-using-TabLayout#implement-fragmentpageradapter学习,我收到了错误消息  android.support.v4.view.ViewPager cannot be cast to android.widget.TextView

我已多次查看代码,但我不知道出了什么问题。

我的res/layout/fragment_page.xml

    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"/>

1 个答案:

答案 0 :(得分:0)

为您的Textview提供ID

<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_text" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"/>

在onCreateView中执行此操作

View view = inflater.inflate(R.layout.fragment_page, container);
TextView textView = (TextView) view.findViewById(R.id.my_text);
textView.setText("Fragment #" + mPage);