程序运行时没有错误,但是当我尝试运行应用程序时,它显示不幸停止。我的调试器不工作。代码如下: 我想在Android中创建一个滑动视图
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ViewPager
android:id="@+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent">
</ViewPager>
</LinearLayout>
MainActivity.java
package com.example.pathak.swipe;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity {
ViewPager viewPager=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
else if(i==1)
{
fragment=new FragmentB();
}
else if(i==2)
{
fragment=new FragmentC();
}
else if(i==3)
{
fragment=new FragmentD();
}
return fragment;
}
@Override
public int getCount() {
return 4;
}
}
fragment.xml之
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#FFCC00"
android:layout_height="match_parent">
</LinearLayout>
FragmentA.java
package com.example.pathak.swipe;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Pathak on 2/3/2016.
*/
public class FragmentA extends Fragment {
@Override
public View onCreateView(LayoutInflater layoutInflater,ViewGroup container,Bundle savedInstanceState)
{
return layoutInflater.inflate(R.layout.fragment_a,container,false);
}
}
类似地,还创建了三个片段和它们的xmls。