Android综合小练习Fragment,解析,Handler,ViewPager

实现效果

逻辑代码--MainActivity

package com.example.week4_day4_viewpagerandfragment;

import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
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.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

	private ViewPager viewPager;// 声明ViewPager
	private List<Fragment> list;//存放Fragment的list集合
	// 解析的数据的地址
	private static final String PATH = "http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
	private static final String PATH1 = "http://litchiapi.jstv.com/api/GetFeeds?column=1&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
	private static final String PATH2 = "http://litchiapi.jstv.com/api/GetFeeds?column=3&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);// 加载布局
		viewPager = (ViewPager) findViewById(R.id.viewpager);// 得到ViewPager对象
		initFragment();// 调用Fragment
		tab();// 导航栏
		// 绑定适配器
		viewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),
				list));
		// 导航栏绑定数据源
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				for (int i = 0; i < list.size(); i++) {
					tvs[i].setBackgroundColor(Color.BLUE);
				}
				tvs[arg0].setBackgroundColor(Color.YELLOW);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void initFragment() {
		list = new ArrayList<Fragment>();
		//新建MyFragment的对象
		MyFragment fragment1 = new MyFragment(this, PATH);
		Bundle bundle = new Bundle();
		bundle.putInt("index", 1);//传值
		fragment1.setArguments(bundle);

		MyFragment fragment2 = new MyFragment(this, PATH1);
		bundle = new Bundle();
		bundle.putInt("index", 2);
		fragment2.setArguments(bundle);

		MyFragment fragment3 = new MyFragment(this, PATH2);
		bundle = new Bundle();
		bundle.putInt("index", 3);
		fragment3.setArguments(bundle);
		list.add(fragment1);
		list.add(fragment2);
		list.add(fragment3);
	}

	private TextView[] tvs;//存放导航标题

	// 导航栏
	public void tab() {
		LinearLayout layout = (LinearLayout) findViewById(R.id.linear1);//加载导航布局
		tvs = new TextView[3];
		for (int i = 0; i < tvs.length; i++) {
			tvs[i] = (TextView) layout.getChildAt(i);
			tvs[i].setTag(i);
			tvs[i].setBackgroundColor(Color.BLUE);//背景颜色
			tvs[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					viewPager.setCurrentItem((Integer) v.getTag());

				}
			});
			tvs[0].setBackgroundColor(Color.YELLOW);
		}

	}

}
Fragment逻辑代码

package com.example.week4_day4_viewpagerandfragment;

import java.util.List;
import java.util.Map;
import com.example.week4_day4_viewpagerandfragment.utils.HttpIntent;
import com.example.week4_day4_viewpagerandfragment.utils.ParserJSON;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

@SuppressLint({ "NewApi", "ValidFragment" })
public class MyFragment extends Fragment {

	private ListView lv;
	private Context context;
	private String path;
	@SuppressLint("HandlerLeak") 
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> lists = (List<Map<String, Object>>) msg.obj;
			lv.setAdapter(new MyAdapter(context, lists));
		};
	};

	@SuppressLint("ValidFragment")
	public MyFragment(Context context, String path) {
		super();
		this.context = context;
		this.path = path;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Bundle bundle = getArguments();
		View view = inflater.inflate(R.layout.item, null);
		lv = (ListView) view.findViewById(R.id.lv);

		if (bundle != null) {
			final int tab = bundle.getInt("index");
			new Thread(){
				public void run() {
					switch (tab) {
					case 1:
						String jsonString = HttpIntent.httpIntent(path);
						List<Map<String, Object>> list = ParserJSON
								.paserJSON(jsonString);
						Message msg = Message.obtain();
						msg.obj = list;
						handler.sendMessage(msg);
						break;
					case 2:
						String jsonString1 = HttpIntent.httpIntent(path);
						List<Map<String, Object>> list2 = ParserJSON
								.paserJSON(jsonString1);
						Message msg2 = Message.obtain();
						msg2.obj = list2;
						handler.sendMessage(msg2);
						break;
					case 3:
						String jsonString2 = HttpIntent.httpIntent(path);
						List<Map<String, Object>> list3 = ParserJSON
								.paserJSON(jsonString2);
						Message msg3 = Message.obtain();
						msg3.obj = list3;
						handler.sendMessage(msg3);
						break;

					default:
						break;
					}
				};
			}.start();
		}
		return view;
	}
}
Fragment适配器

package com.example.week4_day4_viewpagerandfragment;

import java.util.List;

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

/**
 * 自定义FragmentPagerAdapter的适配器 专门存放Fragment数据
 * 
 */
public class MyFragmentAdapter extends FragmentPagerAdapter {

	private List<Fragment> list;

	public MyFragmentAdapter(FragmentManager fm, List<Fragment> list) {
		super(fm);
		this.list = list;

	}

	/**
	 * 根据指定下标返回对应的Fragment对象
	 */
	@Override
	public Fragment getItem(int arg0) {

		return list.get(arg0);
	}

	/**
	 * 适配器中Fragment的数量
	 */
	@Override
	public int getCount() {

		return list.size();
	}

}
网络请求

package com.example.week4_day4_viewpagerandfragment.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpIntent {

	public static String httpIntent(String path) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		URL url;
		try {
			url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setDoInput(true);
			connection.connect();
			if(connection.getResponseCode()==200){
			InputStream in = connection.getInputStream();
			int temp = 0;
			byte[] buffer = new byte[1024];
			while ((temp = in.read(buffer)) != -1) {
				out.write(buffer, 0, temp);
				out.flush();
			}
			return out.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	public static byte[] httpIntents(String path) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		URL url;
		try {
			url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setDoInput(true);
			connection.connect();
			if(connection.getResponseCode()==200){
			InputStream in = connection.getInputStream();
			int temp = 0;
			byte[] buffer = new byte[1024];
			while ((temp = in.read(buffer)) != -1) {
				out.write(buffer, 0, temp);
				out.flush();
			}
			return out.toByteArray();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

}
解析JSON数据

package com.example.week4_day4_viewpagerandfragment.utils;

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

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

public class ParserJSON {
	public static List<Map<String, Object>> paserJSON(String jsonString){
		List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
		try {
			JSONObject object=new JSONObject(jsonString);
			JSONObject object2=object.getJSONObject("paramz");
			JSONArray array=object2.getJSONArray("feeds");
			for (int i = 0; i < array.length(); i++) {
				Map<String, Object> map=new HashMap<String, Object>();
				JSONObject object3=array.getJSONObject(i);
				JSONObject object4=object3.getJSONObject("data");
				String title=object4.getString("subject");
				String content=object4.getString("summary");
				String prc=object4.getString("cover");
				prc="http://litchiapi.jstv.com"+prc;
				map.put("title", title);
				map.put("content", content);
				map.put("prc", prc);
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
		
	}

}

图片缓存

package com.example.week4_day4_viewpagerandfragment.utils;

import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImagAsyncTask extends AsyncTask<String, Void, Bitmap> {

	private Context context;
	private ImageView iv;
	private Map<String, Bitmap> imagCache;

	private String imageUrl = null;

	public ImagAsyncTask(Context context, ImageView iv,
			Map<String, Bitmap> imagCache) {
		this.context = context;
		this.iv = iv;
		this.imagCache = imagCache;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		// TODO Auto-generated method stub
		imageUrl = params[0];
		byte[] buffer = HttpIntent.httpIntents(imageUrl);
		Bitmap bp = null;
		if (buffer != null && buffer.length > 0) {
			bp = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
		}
		return bp;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		imagCache.put(imageUrl, result);// 将图片根据 图片地址缓存
		if (imageUrl.equals(iv.getTag())) {
			iv.setImageBitmap(result);
		}
	}

}
ListView适配器

package com.example.week4_day4_viewpagerandfragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.week4_day4_viewpagerandfragment.utils.ImagAsyncTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyAdapter extends BaseAdapter {

	private Context context;

	private List<Map<String, Object>> list;
	private Map<String, Bitmap> imaMap = new HashMap<String, Bitmap>();

	public MyAdapter(Context context, List<Map<String, Object>> list) {
		super();
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = LayoutInflater.from(context).inflate(R.layout.myadapter,
				null);
		TextView tv1 = (TextView) view.findViewById(R.id.title);
		TextView tv2 = (TextView) view.findViewById(R.id.context);
		ImageView iv = (ImageView) view.findViewById(R.id.image);
		String title = list.get(position).get("title").toString().trim();
		String content = list.get(position).get("content").toString().trim();
		String imagUrl = list.get(position).get("prc").toString().trim();
		iv.setImageResource(R.drawable.ic_launcher);
		tv1.setText(title);
		tv2.setText(content);
		iv.setTag(imagUrl);
		if (!imaMap.containsKey(imagUrl)) {
			ImagAsyncTask task=new ImagAsyncTask(context, iv, imaMap);
			task.execute(imagUrl);
		}else{
			iv.setImageBitmap(imaMap.get(imagUrl));
		}
		return view;
	}

}
布局文件--main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="新闻" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="娱乐" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="体育" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
布局文件--ListView中的item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<ImageView 
    android:id="@+id/image"
    android:layout_width="80dp"
    android:layout_height="80dp"/>

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="14dp"
    android:layout_toRightOf="@+id/image"
    android:text="ss" 
    android:textSize="18sp"/>

<TextView
    android:id="@+id/context"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="14dp"
  android:layout_below="@id/title"
    android:layout_toRightOf="@+id/image"
    android:text="ss" 
    android:singleLine="true"
    android:textSize="15sp"
    android:textColor="#00ff00"/>

</RelativeLayout>
布局文件--ListView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#ff0000"
        android:textSize="18sp"/>

</RelativeLayout>
配置文件--添加网络权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.week4_day4_viewpagerandfragment"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.week4_day4_viewpagerandfragment.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值