新闻类APP模板详解(android版)

1.概述

本文将介绍一个android版新闻类app模板,是本人整合了网上各类资源后整理出来的,希望对大家有所帮助!
iOS版新闻类app模板详见:
新闻类APP模板详解(iOS版)

本模板app截图如下:

新闻类APP模板详解(android版)_第1张图片新闻类APP模板详解(android版)_第2张图片

2.具体实现

该模板主体是一个FragmentActivity,布局文件activity_main.xml如下:


    

    

        

            

                
            

            

            
        
    

    

    


其中:
a. 是titlebar;
b. 定义了左右滑动、展现新闻类型(头条、咨询、招聘等)的控件;
c. 定义了展现各类新闻列表的viewpager,同样响应左右滑动操作,包含顶部滚动广告栏。


对应的MainActivity文件如下:
package com.latu.qingcheng123.activity;

import java.util.ArrayList;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.latu.qingcheng123.R;
import com.latu.qingcheng123.adapter.CategoryFragmentPagerAdapter;
import com.latu.qingcheng123.fragment.CategoryFragment;
import com.latu.qingcheng123.util.BaseTools;
import com.latu.qingcheng123.vo.CategoryItem;
import com.latu.qingcheng123.widget.ColumnHorizontalScrollView;
import com.latu.qingcheng123.widget.DrawerView;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	private ColumnHorizontalScrollView mColumnHorizontalScrollView;
	private LinearLayout mRadioGroup_content;
	private RelativeLayout rl_column;
	private ViewPager mViewPager;
	/** 左阴影部分 */
	public ImageView shade_left;
	/** 右阴影部分 */
	public ImageView shade_right;
	/** head 头部 的左侧菜单 按钮 */
	private ImageView top_head;

	protected SlidingMenu side_drawer;

	/** 屏幕宽度 */
	private int mScreenWidth = 0;
	/** Item宽度 */
	private int mItemWidth = 0;

	private long mExitTime;

	/** 当前选中的栏目 */
	private int columnSelectIndex = 0;
	private ArrayList m_lCategories = new ArrayList();
	private ArrayList m_fragments = new ArrayList();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();
		initSlidingMenu();
	}

	/**
	 * 初始化layout控件
	 */
	private void initView() {
		mScreenWidth = BaseTools.getWindowsWidth(this);
		mItemWidth = mScreenWidth / 7;// 一个Item宽度为屏幕的1/7

		mColumnHorizontalScrollView = (ColumnHorizontalScrollView) findViewById(R.id.mColumnHorizontalScrollView);
		mRadioGroup_content = (LinearLayout) findViewById(R.id.mRadioGroup_content);
		rl_column = (RelativeLayout) findViewById(R.id.rl_column);
		mViewPager = (ViewPager) findViewById(R.id.mViewPager);
		shade_left = (ImageView) findViewById(R.id.shade_left);
		shade_right = (ImageView) findViewById(R.id.shade_right);
		top_head = (ImageView) findViewById(R.id.top_head);
		top_head.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (side_drawer.isMenuShowing()) {
					side_drawer.showContent();
				} else {
					side_drawer.showMenu();
				}
			}
		});
		setChangelView();
	}

	/**
	 * 当栏目项发生变化时候调用
	 * */
	private void setChangelView() {
		initColumnData();
		initTabColumn();
		initFragment();
	}

	/** 获取Column栏目 数据 */
	private void initColumnData() {
		CategoryItem item1 = new CategoryItem();
		item1.categoryID = "0";
		item1.categoryName = "头条";
		m_lCategories.add(item1);

		CategoryItem item2 = new CategoryItem();
		item2.categoryID = "1";
		item2.categoryName = "资讯";
		m_lCategories.add(item2);

		CategoryItem item3 = new CategoryItem();
		item3.categoryID = "2";
		item3.categoryName = "招聘";
		m_lCategories.add(item3);

		CategoryItem item4 = new CategoryItem();
		item4.categoryID = "3";
		item4.categoryName = "二手";
		m_lCategories.add(item4);

		CategoryItem item5 = new CategoryItem();
		item5.categoryID = "4";
		item5.categoryName = "房产";
		m_lCategories.add(item5);

		CategoryItem item6 = new CategoryItem();
		item6.categoryID = "5";
		item6.categoryName = "生活";
		m_lCategories.add(item6);

		CategoryItem item7 = new CategoryItem();
		item7.categoryID = "6";
		item7.categoryName = "婚恋";
		m_lCategories.add(item7);

		CategoryItem item8 = new CategoryItem();
		item8.categoryID = "7";
		item8.categoryName = "轻松";
		m_lCategories.add(item8);
	}

	/**
	 * 初始化Column栏目项
	 * */
	private void initTabColumn() {
		mRadioGroup_content.removeAllViews();
		int count = m_lCategories.size();
		mColumnHorizontalScrollView.setParam(this, mScreenWidth,
				mRadioGroup_content, shade_left, shade_right, rl_column);
		for (int i = 0; i < count; i++) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					mItemWidth, LayoutParams.WRAP_CONTENT);
			params.leftMargin = 5;
			params.rightMargin = 5;
			// TextView localTextView = (TextView)
			// mInflater.inflate(R.layout.column_radio_item, null);
			TextView columnTextView = new TextView(this);
			columnTextView.setTextAppearance(this,
					R.style.top_category_scroll_view_item_text);
			// localTextView.setBackground(getResources().getDrawable(R.drawable.top_category_scroll_text_view_bg));
			columnTextView.setBackgroundResource(R.drawable.radio_buttong_bg);
			columnTextView.setGravity(Gravity.CENTER);
			columnTextView.setPadding(5, 5, 5, 5);
			columnTextView.setId(i);
			columnTextView.setText(m_lCategories.get(i).categoryName);
			columnTextView.setTextColor(getResources().getColorStateList(
					R.color.top_category_scroll_text_color_day));
			if (columnSelectIndex == i) {
				columnTextView.setSelected(true);
			}
			columnTextView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
						View localView = mRadioGroup_content.getChildAt(i);
						if (localView != v)
							localView.setSelected(false);
						else {
							localView.setSelected(true);
							mViewPager.setCurrentItem(i);
						}
					}
					Toast.makeText(getApplicationContext(),
							m_lCategories.get(v.getId()).categoryName,
							Toast.LENGTH_SHORT).show();
				}
			});
			mRadioGroup_content.addView(columnTextView, i, params);
		}
	}

	/**
	 * 初始化Fragment
	 * */
	private void initFragment() {
		int count = m_lCategories.size();
		for (int i = 0; i < count; i++) {
			Bundle data = new Bundle();
			data.putString("name", m_lCategories.get(i).categoryName);
			CategoryFragment fragment = new CategoryFragment();
			fragment.setArguments(data);
			m_fragments.add(fragment);
		}

		CategoryFragmentPagerAdapter mAdapetr = new CategoryFragmentPagerAdapter(
				getSupportFragmentManager(), m_fragments);
		// mViewPager.setOffscreenPageLimit(0);
		mViewPager.setAdapter(mAdapetr);
		mViewPager.setOnPageChangeListener(pageListener);
	}

	/**
	 * ViewPager切换监听方法
	 * */
	public OnPageChangeListener pageListener = new OnPageChangeListener() {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			mViewPager.setCurrentItem(position);
			selectTab(position);
		}
	};

	/**
	 * 选择的Column里面的Tab
	 * */
	private void selectTab(int tab_postion) {
		columnSelectIndex = tab_postion;
		for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
			View checkView = mRadioGroup_content.getChildAt(tab_postion);
			int k = checkView.getMeasuredWidth();
			int l = checkView.getLeft();
			int i2 = l + k / 2 - mScreenWidth / 2;
			// rg_nav_content.getParent()).smoothScrollTo(i2, 0);
			mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
			// mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
			// mItemWidth , 0);
		}
		// 判断是否选中
		for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {
			View checkView = mRadioGroup_content.getChildAt(j);
			boolean ischeck;
			if (j == tab_postion) {
				ischeck = true;
			} else {
				ischeck = false;
			}
			checkView.setSelected(ischeck);
		}
	}

	protected void initSlidingMenu() {
		side_drawer = new DrawerView(this).initSlidingMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (side_drawer.isMenuShowing()) {
				side_drawer.showContent();
			} else {
				if ((System.currentTimeMillis() - mExitTime) > 2000) {
					Toast.makeText(this,
							getResources().getString(R.string.quit_app),
							Toast.LENGTH_SHORT).show();
					mExitTime = System.currentTimeMillis();
				} else {
					finish();
				}
			}
			return true;
		}
		// 拦截MENU按钮点击事件,让他无任何操作
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}

其中,
a. 显示新闻标题的是ColumnHorizontalScrollView控件(横向滚动控件),initColumnData()和initTabColumn()方法完成 了对其的初始化。
b. initFragment()方法初始化了每个标题对应的新闻列表页面,是一种Fragment,叫CategoryFragment。每个CategoryFragment对应一类新闻页面,其中实现了广告栏、新闻列表(上拉和下拉都可以刷新)功能。
c. side_drawer为左侧抽屉菜单,是一个SlidingMenu,需要引入SlidingMenu-master资源,依赖library_123资源工程。关于SlidingMenu-master,可查阅相关资料,本文不做过多介绍。


DrawerView文件定义了左侧抽屉菜单,内容如下:
package com.latu.qingcheng123.widget;

import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.latu.qingcheng123.R;

/**
 * 自定义SlidingMenu 测拉菜单类
 * */
public class DrawerView {
	private final Activity m_activity;
	private SlidingMenu localSlidingMenu;

	private ImageView ivPortrait;
	private TextView tvName;
	private RelativeLayout rlMenu1, rlMenu2, rlMenu3;

	public DrawerView(Activity activity) {
		this.m_activity = activity;
	}

	public SlidingMenu initSlidingMenu() {
		localSlidingMenu = new SlidingMenu(m_activity);
		localSlidingMenu.setMode(SlidingMenu.LEFT); // 设置左右滑菜单
		localSlidingMenu.setTouchModeAbove(SlidingMenu.SLIDING_WINDOW); // 设置要使菜单滑动,触碰屏幕的范围
		// localSlidingMenu.setTouchModeBehind(SlidingMenu.RIGHT);
		localSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); // 设置阴影图片的宽度
		localSlidingMenu.setShadowDrawable(R.drawable.shadow); // 设置阴影图片
		localSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); // SlidingMenu划出时主页面显示的剩余宽度
		localSlidingMenu.setFadeDegree(0.35F); // SlidingMenu滑动时的渐变程度
		localSlidingMenu.attachToActivity(m_activity, SlidingMenu.RIGHT); // 使SlidingMenu附加在Activity右边
		// localSlidingMenu.setBehindWidthRes(R.dimen.left_drawer_avatar_size);
		// //设置SlidingMenu菜单的宽度
		localSlidingMenu.setMenu(R.layout.left_drawer_fragment); // 设置menu的布局文件
		// localSlidingMenu.toggle(); //动态判断自动关闭或开启SlidingMenu
		localSlidingMenu
				.setOnOpenedListener(new SlidingMenu.OnOpenedListener() {
					public void onOpened() {

					}
				});

		initView();
		return localSlidingMenu;
	}

	private void initView() {
		ivPortrait = (ImageView) localSlidingMenu
				.findViewById(R.id.iv_portrait);
		ivPortrait.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(m_activity, "click on portrait!",
						Toast.LENGTH_SHORT).show();
			}
		});

		tvName = (TextView) localSlidingMenu.findViewById(R.id.tv_name);
		tvName.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(m_activity, "click on name!", Toast.LENGTH_SHORT)
						.show();
			}
		});

		rlMenu1 = (RelativeLayout) localSlidingMenu
				.findViewById(R.id.ll_menu_1);
		rlMenu1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(m_activity, "click on menu1!",
						Toast.LENGTH_SHORT).show();
				// // 跳转页面用下方方式
				// m_activity.startActivity(new Intent(m_activity,
				// AboutActivity.class));
			}
		});

		rlMenu2 = (RelativeLayout) localSlidingMenu
				.findViewById(R.id.ll_menu_2);
		rlMenu2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(m_activity, "click on menu2!",
						Toast.LENGTH_SHORT).show();
				// // 跳转页面用下方方式
				// m_activity.startActivity(new Intent(m_activity,
				// AboutActivity.class));
			}
		});

		rlMenu3 = (RelativeLayout) localSlidingMenu
				.findViewById(R.id.ll_menu_3);
		rlMenu3.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(m_activity, "click on menu3!",
						Toast.LENGTH_SHORT).show();
				// // 跳转页面用下方方式
				// m_activity.startActivity(new Intent(m_activity,
				// AboutActivity.class));
			}
		});
	}
}
对应的布局文件left_drawer_fragment.xml如下:


    

        

        
    

    

    

        

            

                
            

            

            

                
            

            

            

                
            

            
        
    

包含头像、名称、3个菜单项。


如上所述,CategoryFragment实现了获取新闻、显示列表等一系列功能,代码如下:
package com.latu.qingcheng123.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.latu.qingcheng123.R;
import com.latu.qingcheng123.adapter.NewsAdapter;
import com.latu.qingcheng123.util.GlobalParam;
import com.latu.qingcheng123.vo.AdsItem;
import com.latu.qingcheng123.vo.NewsItem;
import com.latu.qingcheng123.widget.xlistview.XListView;
import com.latu.qingcheng123.widget.xlistview.XListView.IXListViewListener;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class CategoryFragment extends Fragment implements IXListViewListener {

	private Activity m_activity;
	private String m_categoryName;

	private XListView mListView;
	private NewsAdapter mAdapter;
	private LinkedList newsList = new LinkedList();
	private ArrayList adsList = new ArrayList();
	private Handler mHandler;
	private ScheduledExecutorService scheduledExecutorService; // 控制广告滚动
	private int indexNew = 20;
	private int indexOld = 20;

	private static final String[] URLS = {
			"https://img-my.csdn.net/uploads/201403/03/1393854094_4652.jpg",
			"https://img-my.csdn.net/uploads/201403/03/1393854084_6138.jpg",
			"https://img-my.csdn.net/uploads/201403/03/1393854084_1323.jpg",
			"https://img-my.csdn.net/uploads/201403/03/1393854084_8439.jpg",
			"https://img-my.csdn.net/uploads/201403/03/1393854083_6511.jpg",
			"https://img-my.csdn.net/uploads/201403/03/1393854083_2323.jpg" };

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		m_categoryName = args != null ? args.getString("name") : "";
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View viewContent = LayoutInflater.from(m_activity).inflate(
				R.layout.fragment_category, null);

		mListView = (XListView) viewContent.findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		mAdapter = new NewsAdapter(m_activity, newsList, adsList);
		mListView.setAdapter(mAdapter);
		// mListView.setPullLoadEnable(false);
		// mListView.setPullRefreshEnable(false);
		mListView.setXListViewListener(this);
		mHandler = new Handler();

		getAds();
		getNews();
		mAdapter.notifyDataSetChanged();

		return viewContent;
	}

	@Override
	public void onStart() {
		// if (scheduledExecutorService != null)
		// {
		// scheduledExecutorService.shutdown();
		// }
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2,
				TimeUnit.SECONDS);
		super.onStart();
	}

	@Override
	public void onStop() {
		if (scheduledExecutorService != null) {
			scheduledExecutorService.shutdown();
		}
		super.onStop();
	}

	/**
	 * 广告滚动线程
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			if (mAdapter != null) {
				synchronized (mAdapter) {
					mAdapter.scrollAds();
				}
			}
		}

	}

	private void getAds() {
		adsList.clear();

		AdsItem item1 = new AdsItem();
		item1.adsId = "1";
		item1.title = "广告1";
		item1.imgURL = "https://img-my.csdn.net/uploads/201404/13/1397393290_5765.jpeg";
		adsList.add(item1);

		AdsItem item2 = new AdsItem();
		item2.adsId = "2";
		item2.title = "广告内容2";
		item2.imgURL = "https://img-my.csdn.net/uploads/201403/03/1393854084_8439.jpg";
		adsList.add(item2);

		AdsItem item3 = new AdsItem();
		item3.adsId = "3";
		item3.title = "广告推广信息3";
		item3.imgURL = "https://img-my.csdn.net/uploads/201403/03/1393854083_2323.jpg";
		adsList.add(item3);
	}

	private void getNews() {
		for (int i = 0; i != 5; ++i) {
			NewsItem item = new NewsItem();
			item.newsId = "" + indexOld;
			item.leftImgURL = URLS[i % 6];
			item.title = "新闻标题" + indexOld;
			item.source = "新浪新闻";
			item.commentNum = indexOld;

			newsList.add(item);
			indexOld++;
		}
	}

	private void getLatestNews() {
		for (int i = 0; i != 5 && indexNew > 0; ++i) {
			indexNew--;
			NewsItem item = new NewsItem();
			item.newsId = "" + indexNew;
			item.leftImgURL = URLS[i % 6];
			item.title = "新闻标题" + indexNew;
			item.source = "新浪新闻";
			item.commentNum = indexNew;

			newsList.addFirst(item);

		}
	}

	private void onFinishLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(GlobalParam.g_dateFormat.format(new Date(
				System.currentTimeMillis())));
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				getLatestNews();
				mAdapter.notifyDataSetChanged();
				onFinishLoad();
			}
		}, 1000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				getNews();
				mAdapter.notifyDataSetChanged();
				onFinishLoad();
			}
		}, 1000);
	}

	/** 此方法意思为fragment是否可见 ,可见时候加载数据 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (isVisibleToUser) {

		} else {
			// fragment不可见时不执行操作
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public void onAttach(Activity activity) {
		this.m_activity = activity;
		super.onAttach(activity);
	}

}
其中,
a.  展现新闻列表的是XListView,是一个响应下拉和上拉刷新的自定义ListView,需要实现IXListViewListener接口。对应的布局文件fragment_category.xml比较简单,就一个listview。


    

    
    


b. 组织和显示新闻列表的adapter(数据适配器)是一个NewsAdapter对象mAdapter。NewsAdapter自定义了广告和新闻的组织、显示方式。使用时,需要根据您的数据要求做相应的调整。代码如下:
package com.latu.qingcheng123.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.latu.qingcheng123.R;
import com.latu.qingcheng123.util.BaseTools;
import com.latu.qingcheng123.util.GlobalParam;
import com.latu.qingcheng123.util.ProfessionalTools;
import com.latu.qingcheng123.vo.AdsItem;
import com.latu.qingcheng123.vo.NewsItem;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewsAdapter extends BaseAdapter {

	private Context mContext;
	// 新闻列表
	private List newsList;
	// 广告列表
	private List adsList;
	private NewsViewHolder mHolder;
	private LayoutInflater mInflater;

	private ViewPager vpAds;
	private AdsAdapter adsAdapter;
	private TextView tvAdsTitle;
	private LinearLayout llAdsPage;
	private List ads_imageViews; // 滑动的图片集合
	private List ads_dots; // 图片标题正文的那些点
	private int ads_currentItem = 0; // 当前图片的索引号

	public NewsAdapter(Context context, List newsList,
			List adsList) {
		super();
		this.mContext = context;
		this.newsList = newsList;
		this.adsList = adsList;
		mInflater = LayoutInflater.from(mContext);

		ads_imageViews = new ArrayList();
		ads_dots = new ArrayList();
		adsAdapter = new AdsAdapter();
	}

	@Override
	public int getCount() {
		if (adsList != null && adsList.size() > 0) {
			if (newsList != null && newsList.size() > 0) {
				return newsList.size() + 1;
			} else {
				return 1;
			}
		} else {
			if (newsList != null && newsList.size() > 0) {
				return newsList.size();
			} else {
				return 0;
			}
		}
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (adsList != null && adsList.size() > 0) {
			if (position == 0) {
				convertView = mInflater.inflate(R.layout.ads_head, null);

				tvAdsTitle = (TextView) convertView
						.findViewById(R.id.tv_ads_title);
				llAdsPage = (LinearLayout) convertView
						.findViewById(R.id.ll_ads_page);
				vpAds = (ViewPager) convertView.findViewById(R.id.vp_ads);
				vpAds.setAdapter(adsAdapter);
				vpAds.setOnPageChangeListener(new MyPageChangeListener());

				// llAdsPage.removeAllViews();
				// vpAds.removeAllViews();
				ads_dots.clear();
				ads_imageViews.clear();
				for (int i = 0; i < adsList.size(); i++) {
					final AdsItem item = adsList.get(i);
					ImageView imageView = new ImageView(mContext);
					setImageViewPic(imageView, item.imgURL);
					imageView.setScaleType(ScaleType.CENTER_CROP);
					imageView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Toast.makeText(mContext, item.title,
									Toast.LENGTH_SHORT).show();
						}
					});
					ads_imageViews.add(imageView);

					View vDot = new View(mContext);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
							10, 10);
					lp.setMargins(5, 0, 5, 0);
					vDot.setLayoutParams(lp);
					if (i == ads_currentItem) {
						vDot.setBackgroundResource(R.drawable.dot_focused);
					} else {
						vDot.setBackgroundResource(R.drawable.dot_normal);
					}
					llAdsPage.addView(vDot);
					ads_dots.add(vDot);
				}
				vpAds.setCurrentItem(ads_currentItem);
				tvAdsTitle.setText(adsList.get(ads_currentItem).title);

				return convertView;
			} else {
				convertView = mInflater.inflate(R.layout.news_list_item, null);
				mHolder = new NewsViewHolder();

				mHolder.llCommon = (LinearLayout) convertView
						.findViewById(R.id.ll_common);
				mHolder.ivLeftImg = (ImageView) convertView
						.findViewById(R.id.iv_left_image);
				mHolder.tvTitle = (TextView) convertView
						.findViewById(R.id.tv_title);
				mHolder.tvSource = (TextView) convertView
						.findViewById(R.id.tv_source);
				mHolder.tvCommentCount = (TextView) convertView
						.findViewById(R.id.tv_comment_count);

				if (newsList != null && newsList.size() > position - 1) {
					NewsItem item = newsList.get(position - 1);
					mHolder.tvTitle.setText(item.title);
					mHolder.tvSource.setText(item.source);
					mHolder.tvCommentCount.setText("" + item.commentNum);
					setImageViewPic(mHolder.ivLeftImg, item.leftImgURL);
				}

				return convertView;
			}
		} else {
			convertView = mInflater.inflate(R.layout.news_list_item, null);
			mHolder = new NewsViewHolder();

			mHolder.llCommon = (LinearLayout) convertView
					.findViewById(R.id.ll_common);
			mHolder.ivLeftImg = (ImageView) convertView
					.findViewById(R.id.iv_left_image);
			mHolder.tvTitle = (TextView) convertView
					.findViewById(R.id.tv_title);
			mHolder.tvSource = (TextView) convertView
					.findViewById(R.id.tv_source);
			mHolder.tvCommentCount = (TextView) convertView
					.findViewById(R.id.tv_comment_count);

			if (newsList != null && newsList.size() > position) {
				NewsItem item = newsList.get(position);
				mHolder.tvTitle.setText(item.title);
				mHolder.tvSource.setText(item.source);
				mHolder.tvCommentCount.setText("" + item.commentNum);
				setImageViewPic(mHolder.ivLeftImg, item.leftImgURL);
			}

			return convertView;
		}
	}

	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (vpAds != null) {
				vpAds.setCurrentItem(ads_currentItem);// 切换当前显示的图片
			}
		};
	};

	/**
	 * 广告滚动
	 */
	public void scrollAds() {
		ads_currentItem = (ads_currentItem + 1) % ads_imageViews.size();
		handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			ads_currentItem = position;
			tvAdsTitle.setText(adsList.get(position).title);
			ads_dots.get(oldPosition).setBackgroundResource(
					R.drawable.dot_normal);
			ads_dots.get(position)
					.setBackgroundResource(R.drawable.dot_focused);
			oldPosition = position;
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 填充ViewPager页面的适配器
	 * 
	 */
	private class AdsAdapter extends PagerAdapter {

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

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			ViewPager vp = (ViewPager) arg0;
			vp.addView(ads_imageViews.get(arg1));
			return ads_imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			ViewPager vp = (ViewPager) arg0;
			vp.removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}
	}

	private void setImageViewPic(final ImageView iv, String picUrl) {
		if (picUrl != null && !"".equals(picUrl)) {
			String picNameTemp = ProfessionalTools.MD5(picUrl);
			final String strFilePath = BaseTools.getImageCachePath(mContext)
					+ File.separator + picNameTemp;
			File picFile = new File(strFilePath);
			if (picFile.exists()) // 本地有缓存
			{
				Bitmap bitmap = BaseTools.getLocalBitmap(strFilePath);
				if (bitmap != null) {
					iv.setImageBitmap(bitmap);
				}
			} else {
				ImageRequest imageRequest = new ImageRequest(picUrl,
						new Response.Listener() {
							@Override
							public void onResponse(Bitmap response) {
								iv.setImageBitmap(response);
								BaseTools.saveBitmapInLocal(response,
										strFilePath);
							}
						}, 0, 0, Config.RGB_565, new Response.ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError arg0) {
								iv.setImageResource(R.drawable.loadpic_empty_listpage);
							}
						});
				GlobalParam.g_volleyRequestQueue.add(imageRequest);
			}
		}
	}

	static class NewsViewHolder {
		LinearLayout llCommon;
		ImageView ivLeftImg;
		TextView tvTitle;
		TextView tvSource;
		TextView tvCommentCount;
	}

}
其中,
a. 显示广告的布局文件为ads_head.xml,用一个自定义ViewPager(AdsViewPager)来显示滚动广告。


    

    

        

        
        
    


b. 显示新闻的布局文件为news_list_item.xml,内容比较简单,这里就不贴了。
c. 广告滚动是外部类CategoryFragment定时调用NewsAdapter的scrollAds()方法来实现的。
d. 广告列表也有自身的adapter,AdsAdapter。

代码部分讲到这里,大伙可以下载工程源码进行研究!

3.源码


模板工程源码:

http://download.csdn.net/detail/chadeltu/8363897









你可能感兴趣的:(android)