Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android ViewPager實例代碼介紹2。

Android ViewPager實例代碼介紹2。

編輯:關於Android編程

以前寫過一篇ViewPager:內容content+指示點的Demo;

這篇文章繼續介紹ViewPager:內容content+標題title的Demo。

實現效果圖:


\


<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+1LS0+sLro7o8L3A+CjxwPrK8vtbOxLz+o7phY3Rpdml0eV9tYWluOjwvcD4KPHA+PHByZSBjbGFzcz0="brush:java;">
f1.xml(體育新聞布局文件):



    


f2.xml(娛樂新聞布局文件):



    


f3.xml(軍事新聞布局文件):



    

        

        

        
    


代碼文件:

MainActivity:

package com.fragmentdemo11_viewpager;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;

public class MainActivity extends Activity {
	private ViewPager viewPager;
	private List title;
	private List content;
	private LayoutInflater inflater;
	private MyViewPagerAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		viewPager = (ViewPager) findViewById(R.id.viewPager);
		content = new ArrayList();
		inflater = LayoutInflater.from(this);
		/**
		 * 添加內容content
		 */
		content.add(inflater.inflate(R.layout.f1, null));
		content.add(inflater.inflate(R.layout.f2, null));
		content.add(inflater.inflate(R.layout.f3, null));
		
		/**
		 * 添加每個內容對應的標題title
		 */
		title = new ArrayList();
		title.add("體育新聞");
		title.add("娛樂新聞");
		title.add("軍事新聞");
		
		adapter = new MyViewPagerAdapter(this,content,title);
		viewPager.setAdapter(adapter);
		
	}
}

ViewPager適配器:

package com.fragmentdemo11_viewpager;

import java.util.List;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
/**
 * ViewPager適配器
 */
public class MyViewPagerAdapter extends PagerAdapter {
	private Context context;
	private List content;
	private List title;

	public MyViewPagerAdapter(Context context, List content,
			List title) {
		this.context = context;
		this.content = content;
		this.title = title;
	}
	/**
	 * 初始化
	 */
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		((ViewPager)container).addView(content.get(position));
		return content.get(position);
	}
	/**
	 * title
	 */
	@Override
	public CharSequence getPageTitle(int position) {
		return title.get(position);
	}

	@Override
	public int getCount() {
		return content.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}
	/**
	 * 銷毀
	 */
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		((ViewPager)container).removeView(content.get(position));
	}
}



源代碼下載:

點擊下載源碼


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved