新闻客户端

项目名称:新闻客户端

开发语言:java 

开发环境:Eclipseandroid SDK

项目简介:一款基于Android系统的新闻浏览软件,实现从网络获取新闻数据,下拉刷新,下拉加载更多,等功能

 

新闻客户端_第1张图片                       新闻客户端_第2张图片

 

这里主要是实现上面的ViewPager和下面的ListView列表一起上下滚动的效果,使用的是第三方包ImageSlider_library,这里导入第三包的时候需要注意,必须勾选(copy project into 

Workspace)这个选项,就是把你导入的第三包复制到和你当前的项目同一工作空间下面,这样才能找到,然后就是添加第三包了,右键你的项目选择,properties__Android__libary_add_apply_ok就行了,

这个页面效果布局也是一个Listview.只是上面的ViewPagerListView设置的头HeadView

private View mHeaderView;
private SliderLayout mSliderLayout;


 

首先要定义两个变量,他们的包就是你所导入的第三方包;

然后你需要新建一个xml,布局就是ListView的头部布局




    

    


 

这里引用的就是第三包的布局了

<com.scxh.slider.library.SliderLayout

然后就是把布局转换成View对象了

mHeaderView = inflater.inflate(
				R.layout.fragment_imageslider_listview_headview, null);
mSliderLayou=(SliderLayout)mHeaderView.findViewById(R.id.my_slider);

然后就是设置到ListView了
HashMap http_url_maps = getData();
		for (String name : http_url_maps.keySet()) {
		TextSliderView textSliderView= new TextSliderView(getActivity());

			textSliderView.description(name).image(http_url_maps.get(name))
					.setScaleType(BaseSliderView.ScaleType.Fit);

			mSliderLayout.addSlider(textSliderView);
		}

		mListView.addHeaderView(mHeaderView);

		MyBaseAdapter mAdapter = new MyBaseAdapter(getActivity());
		mListView.setAdapter(mAdapter);

		mAdapter.setData(getDataContent());


 

当然显示的内容肯定是要有个数据源,HashMap的数据和对象的数组都行,这里是从网络获取的

当我从网络取到数据的时候,从数据数组里面任意取几项放到一个新的数组里面,这个数据就是我这里的数据源

ArrayList imageList = new ArrayList();
int count = 4;
if (count > 0) {
					imageList.add(content);
					count--;
				}
这里表示我只取4项,然后添加到数组里面,作为数据源

setSliderImage(imageList);

public void setSliderImage(ArrayList imageList) {
		mSliderLayout.removeAllSliders();
		for (ContentBean bean : imageList) {
			TextSliderView textSliderView = new TextSliderView(getActivity());
			Log.v("tag", "bean.getImgsrc() >>> " + bean.getImgsrc());
			textSliderView.description(bean.getTitle()).image(bean.getImgsrc())
					.setScaleType(BaseSliderView.ScaleType.Fit);

			mSliderLayout.addSlider(textSliderView);
		}
	}	


 

这样头部的设置就完成了,下面的LsitView就比较简单了,把从网络获取到所有数据取你需要显示的东西,添加到对象里面,再建一个动态数组List<对象>就是适配器的数据源了,再自定义适配器,然后ListView设置适配器就行了

这样这个界面就完成了;

在这里界面显示有个难点,就是ListView的单项布局有两种显示方式

新闻客户端_第3张图片

 

List列表的两种显示方式的实现
这里首先你肯定需要两个XML,然后就是在自定义的适配器中多重写几个方法
private final static int TYPE_ONE = 0; // 类型序号必须从0开始
private final static int TYPE_TWO = 1;
private final static int TYPE_COUNT = 2; // listview类型个数

@Override
public int getViewTypeCount() {
			return TYPE_COUNT;
		}
@Override
		public int getItemViewType(int position) {
			ContentBean typeBean = (ContentBean) getItem(position);
			ArrayList imageArray = typeBean.getImgextra();
			if (imageArray != null) {
				return TYPE_ONE;
			} else {
				return TYPE_TWO;
			}
		}
这个方法是需要你传的数据过来,判断你去加载哪种布局

public View getTypeOneView(int position, View convertView,
				ViewGroup parent) {
加载第一种布局
public View getTypeOneView(int position, View convertView,
				ViewGroup parent) {
加载第二种布局
	@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (getItemViewType(position) == TYPE_ONE) {
				return getTypeOneView(position, convertView, parent);
			} else {
				return getTwoTypeView(position, convertView, parent);
			}
		}
调用getItemViewType决定调用哪个方法去加载那种布局
这样这个界面就完成了;


 

二.下拉刷新,下拉加载更多

 新闻客户端_第4张图片                           新闻客户端_第5张图片

这里使用的是XListView的下拉刷新,上拉加载更多的效果

首先你还是需要导入第三方包XlistView;

这里需要改变的只是将你主布局XML里面的ListVIiew改成导入的第三包的XListView


 

使用就是在使用的类里面实现IXListViewListener接口,并实现里面的两个方法
@Override
	public void onRefresh() {
//刷新
	}

	@Override
	public void onLoadMore() {
		//加载更多
		}

	}

在方法里面写需要实现的功能就行了;

在这里也有一个难点,就是当加载更多的时候List列表显示的数据问题,我们希望实现数据累加的,而不是只是显示一页,的数据,这也需要在自定义适配器里面重写,两个方法
public void setAdapterData(ArrayList list) {
			this.list = list;
			notifyDataSetChanged();
		}
当第一页的时候直接设置

public void addAdapterData(ArrayList list) {
			this.list.addAll(list);
			notifyDataSetChanged();
		}
当不是第一页的时候就累加list数据源

侧滑切换功能的实现

首先你还是需要导入第三方包slidingmenu_library

然后新建一个你侧滑时候出现的Fragment

package com.example.pressclient;

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

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.ListView;
import android.widget.SimpleAdapter;

public class SlidingmenuFragment extends Fragment {
	private ListView mListView;

	public static SlidingmenuFragment newInstance() {

		return new SlidingmenuFragment();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.slidingmenu_menu_layout,
				container, false);
		mListView = (ListView) view.findViewById(R.id.slidingmenu_list);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		GetData();
		String[] from = { "icon", "text" };
		int[] to = { R.id.sm_list_item_icon, R.id.sm_list_item_text };
		SimpleAdapter adapter = new SimpleAdapter(getActivity(), GetData(),
				R.layout.slidingmenu_list_item, from, to);
		mListView.setAdapter(adapter);
	}

	private List> GetData() {
		List> list = new ArrayList>();
		HashMap item = new HashMap();
		item.put("icon", R.drawable.sliding_navigation_tab_pics);
		item.put("text", "图片");
		list.add(item);

		item = new HashMap();
		item.put("icon", R.drawable.sliding_navigation_tab_video);
		item.put("text", "视频");
		list.add(item);

		item = new HashMap();
		item.put("icon", R.drawable.sliding_navigation_tab_weather);
		item.put("text", "天气");
		list.add(item);

		item = new HashMap();
		item.put("icon", R.drawable.sliding_navigation_tab_map_1);
		item.put("text", "地图");
		list.add(item);

		item = new HashMap();
		item.put("icon", R.drawable.sliding_navigation_tab_more);
		item.put("text", "更多");
		list.add(item);
		return list;

	}

}


 

然后就是在主Activity里面引用这个Fragment了
private void setBehindContentView() {
		setBehindContentView(R.layout.slidingmenu_item_layout);
		getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.slidingmenu_item_layout,
						SlidingmenuFragment.newInstance()).commit();

		SlidingMenu sm = getSlidingMenu();
		sm.setSlidingEnabled(true);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setBehindScrollScale(0);
		sm.setFadeDegree(0.25f);
	}
这样侧滑就实现了


 

新闻列表点击内容的实现

@Override
	public void onItemClick(AdapterView parent, View view, int position,
			long id) {
		Intent intent = new Intent(getActivity(), ContentActivity.class);

		ContentBean content = (ContentBean) parent.getAdapter().getItem(
				position);
		String docid = content.getDocid();
		intent.putExtra("docid", docid);
		startActivity(intent);


 

package com.example.pressclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.pressclient.ConnectionUtils.CallConnectionInterface;
import com.example.pressclient.ConnectionUtils.Method;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class ContentActivity extends Activity implements OnClickListener{
	private WebView mWebView;
	private TextView mTitle, mSource, mTime, mPicNumber;
	private ImageView mImageView;
	private String docid = "A90HHI6I00014SEH";// 新闻ID ,从新闻列表项目获取
	private String url;
	private ProgressBar mProgressBar;
	private ConnectionUtils connectionUtils;
	private AsyncLoaderImage asyncLoaderImage;
	private ImageView mBackBtn;
	private static final int HANDLER_ERROR = 1;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HANDLER_ERROR:
				String errorResponse = (String) msg.obj;
				Toast.makeText(ContentActivity.this, errorResponse, Toast.LENGTH_SHORT)
						.show();
				
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_item_content);
		
		mWebView = (WebView) findViewById(R.id.ContentWebView);
		mTitle = (TextView) findViewById(R.id.content_title);
		mSource = (TextView) findViewById(R.id.content_source_text);
		mTime = (TextView) findViewById(R.id.content_time);
		mImageView = (ImageView) findViewById(R.id.content_image);
		mPicNumber = (TextView) findViewById(R.id.pic_number);
		mProgressBar=(ProgressBar) findViewById(R.id.content_progress);
		mBackBtn=(ImageView) findViewById(R.id.back_btn);
		mBackBtn.setOnClickListener(this);
		
		mImageView.setVisibility(View.GONE);

		connectionUtils = new ConnectionUtils();
		asyncLoaderImage = AsyncLoaderImage.getInstanceAsyncLoaderImage();
		GetData();

	}

	private void GetData() {
		Intent intent = getIntent();
		docid = intent.getStringExtra("docid");
		url = "http://c.m.163.com/nc/article/" + docid + "/" + "full.html";
		connectionUtils.asyncTaskConnection(url, Method.GET,
				new CallConnectionInterface() {

					@Override
					public void onExecuteResponse(String response) {
						try {
							mProgressBar.setVisibility(View.VISIBLE);
							JSONObject jsonObject = new JSONObject(response);
							JSONObject bodyObj = jsonObject
									.getJSONObject(docid);
							String body = bodyObj.getString("body");
							final String title = bodyObj.getString("title");
							String source = bodyObj.getString("source");
							String ptime = bodyObj.getString("ptime");

							mTitle.setText(title);
							mSource.setText("来源:" + source);
							mTime.setText(ptime);
							mWebView.loadDataWithBaseURL(null, body,
									"text/html", "utf-8", null);
							if (bodyObj.has("img")) {

								final ArrayList imageUrls = new ArrayList();
								JSONArray imageArray = bodyObj
										.getJSONArray("img");
								for (int i = 0; i < imageArray.length(); i++) {
									JSONObject obj = imageArray
											.getJSONObject(i);
									String imagrUrl = obj.getString("src");
									imageUrls.add(imagrUrl);
								}
								Log.e("TAG", "imageUrls======"+imageUrls);
								
								if (imageUrls != null&& imageArray.length() > 0) {
									Log.e("TAG", "imageUrls======"+imageUrls);
									mImageView.setVisibility(View.VISIBLE);
									int count = imageArray.length();
									mPicNumber.setText("共" + count + "张");
									String url = imageUrls.get(0);
									asyncLoaderImage.loadBitmap(getResources(),
											url, mImageView);
									mImageView.setOnClickListener(new OnClickListener() {

												@Override
												public void onClick(View v) {
													Intent intent = new Intent(ContentActivity.this,
															HttpImagevViewPager.class);
													intent.putExtra("imageUrls",imageUrls);
													intent.putExtra("title", title);
													startActivity(intent);
												}
											});
								}
							} else {
								mImageView.setVisibility(View.GONE);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
						mProgressBar.setVisibility(View.GONE);

					}

					@Override
					public void onErrorResponse(String errorResponse) {
						Message msg = Message.obtain();
						msg.what = HANDLER_ERROR;
						msg.obj = errorResponse;
						mHandler.sendMessage(msg);
					}
				});

	}

	public Bitmap getBitmapByHttp(String httpUrl) {
		InputStream ins = null;
		try {
			URL url = new URL(httpUrl);
			ins = url.openStream();

			Bitmap bitmap = BitmapFactory.decodeStream(ins);

			return bitmap;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ins != null) {
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_btn:
//			Intent intent=new Intent(this, MainActivity.class);
//			startActivity(intent);
			this.finish();
			System.exit(0);
			
			break;

		default:
			break;
		}
		
	}

}




主页Tab切换和滑动效果的嵌套实现

		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.HeadlineTab:
					mViewPager.setCurrentItem(0);

					break;

				case R.id.RecreationTab:
					mViewPager.setCurrentItem(1);

					break;

				case R.id.SportsTab:
					mViewPager.setCurrentItem(2);

					break;
				case R.id.FinanceTab:
					mViewPager.setCurrentItem(3);

					break;
				case R.id.ScienceTab:
					mViewPager.setCurrentItem(4);

					break;
				}

			}
		});
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					mHeadlineTab.setChecked(true);
					break;

				case 1:
					mRecreationTab.setChecked(true);
					break;
				case 2:
					mSportsTab.setChecked(true);
					break;
				case 3:
					mFinanceTab.setChecked(true);
					break;
				case 4:
					mScienceTab.setChecked(true);
					break;
				}

			}

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

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

	}


 

你可能感兴趣的:(Android)