Android Tab界面的实现-ViewPager+TabPageIndicator

  今天我来说说ViewPager+tabPageIndicator来实现tab界面。首先tabPageIndicator是在第三方的library包里面-- viewPagerlibrary,在githup上可以下载,我们需要将它导入eclipse中,然后在关联它。当我们使用这个包的时候,有一个问题需要注意:可能主工程中会报错,但是我们又不知道是哪里错了,最好看看libs下的v4包,一定要保证主工程和library中的v4包要么一模一样,要么只有一个,所以要么将其中一个v4包用另一个v4覆盖,或者直接删除一个包。
  好的,现在直接贴代码

MainActivity布局文件代码


    

        
    

    

        
        
    
    
        
    


MainActivity代码
package com.example.android_tab4;

import com.example.Util.Myadapter;
import com.viewpagerindicator.TabPageIndicator;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Window;

public class MainActivity extends FragmentActivity {
    private ViewPager viewpager = null;
    private TabPageIndicator tabPageIndicator = null;
    private Myadapter myadapter = null;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() 
    {
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        tabPageIndicator = (TabPageIndicator) findViewById(R.id.TabPageIndicator);
        myadapter = new Myadapter(getSupportFragmentManager());
        viewpager.setAdapter(myadapter);
        tabPageIndicator.setViewPager(viewpager, 0);
    }
}
MyFragment代码
package com.example.Util;

import com.example.android_tab4.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment extends Fragment{
    String string = null;
    public MyFragment(int position)
    {
        string = Myadapter.string[position];
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        
        TextView textview = (TextView) view.findViewById(R.id.textview);
        textview.setText(string);
        return view;
    }
}
MyFragment布局文件代码


    


MyAdapter代码
package com.example.Util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class Myadapter extends FragmentPagerAdapter{
    public  static String string[] = { "课程", "问答", "求课", "学习", "计划" };
    public Myadapter(FragmentManager fm) {
        super(fm);
    }

    public Fragment getItem(int arg0) {
        MyFragment myfragment = new MyFragment(arg0);
        return myfragment;
    }
    public int getCount() {
        return string.length;
    }
    public CharSequence getPageTitle(int position) {

        return string[position];
    }

}
top.xml代码


    
    

你可能感兴趣的:(Android Tab界面的实现-ViewPager+TabPageIndicator)