一:
此导航栏是TextView实现的
清单文件加权限
主逻辑代码文件:
<span style="font-size:18px;">package com.example.day20_viewpage2;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
private static final String path1="http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
private static final String path2="http://litchiapi.jstv.com/api/GetFeeds?column=1&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
private static final String path3="http://litchiapi.jstv.com/api/GetFeeds?column=3&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
ViewPager vp,vp_fg;
List<ImageView> list;
List<Fragment> list_fg;
int imgs[]={R.drawable.slide1,R.drawable.slide2,R.drawable.slide3};
//存放导航标题
TextView tvs[]=new TextView[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTab();
vp=(ViewPager) findViewById(R.id.vp);
list=new ArrayList<ImageView>();
for (int i = 0; i < imgs.length; i++) {
ImageView iv=new ImageView(this);
iv.setImageResource(imgs[i]);
list.add(iv);
}
MyAdapter adapter=new MyAdapter();
vp.setAdapter(adapter);
vp.setCurrentItem(Integer.MAX_VALUE/2-Integer.MAX_VALUE/2%list.size());
handler.sendEmptyMessageDelayed(1,2000);
vp_fg=(ViewPager) findViewById(R.id.vp_fg);
list_fg=new ArrayList<Fragment>();
MyFragment fragment1=new MyFragment(MainActivity.this,path1);
Bundle bundle=new Bundle();
bundle.putInt("index", 1);
fragment1.setArguments(bundle);
MyFragment fragment2=new MyFragment(MainActivity.this,path2);
bundle=new Bundle();
bundle.putInt("index", 2);
fragment2.setArguments(bundle);
MyFragment fragment3=new MyFragment(MainActivity.this,path3);
bundle=new Bundle();
bundle.putInt("index", 3);
fragment3.setArguments(bundle);
list_fg.add(fragment1);
list_fg.add(fragment2);
list_fg.add(fragment3);
MyFragmentAdapter fgAdapter=new MyFragmentAdapter(getSupportFragmentManager());
vp_fg.setAdapter(fgAdapter);
vp_fg.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
for (int i = 0; i < list_fg.size(); i++) {
tvs[i].setBackgroundColor(Color.GRAY);
}
tvs[arg0].setBackgroundColor(Color.BLUE);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public void initTab()
{
LinearLayout layout_title=(LinearLayout) findViewById(R.id.layout_title);
for (int i = 0; i < tvs.length; i++) {
tvs[i]=(TextView) layout_title.getChildAt(i);
tvs[i].setTag(i);
tvs[i].setBackgroundColor(Color.GRAY);
tvs[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
vp_fg.setCurrentItem((Integer) v.getTag());
}
});
tvs[0].setBackgroundColor(Color.BLUE);
}
}
//轮播
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
vp.setCurrentItem(vp.getCurrentItem()+1);
sendEmptyMessageDelayed(1, 2000);
};
};
class MyAdapter extends PagerAdapter
{
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(list.get(position%list.size()));
return list.get(position%list.size());
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(list.get(position%list.size()));
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
}
//自定义一个adapter 专门放Fragment数据的
class MyFragmentAdapter extends FragmentPagerAdapter
{
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
//根据指定下标 返回对应的Fragment对象
@Override
public Fragment getItem(int arg0) {
return list_fg.get(arg0);
}
// 适配器中Fragment的数量
@Override
public int getCount() {
return list_fg.size();
}
}
}
</span>
主布局文件:
<span style="font-size:18px;"><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/layout_title"
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="新闻"
android:textSize="24sp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="糗事"
android:textSize="24sp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="茶百科"
android:textSize="24sp"/>
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="wrap_content"
android:layout_height="100dp"
/>
<android.support.v4.view.ViewPager
android:id="@+id/vp_fg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</span>
fragment逻辑代码文件:
<span style="font-size:18px;">package com.example.day20_viewpage2;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.example.day20_viewpage2.adapter.FAdapter;
import com.example.day20_viewpage2.utils.ParserData1;
import com.example.day20_viewpage2.utils.RequestData;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("ValidFragment")
public class MyFragment extends Fragment implements OnItemClickListener{
ListView lv;
Context context;
FAdapter adapter;
String path;
@SuppressLint("ValidFragment")
public MyFragment(Context context,String path) {
this.context = context;
this.path = path;
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
List<Map<String, Object>> lists = (List<Map<String, Object>>) msg.obj;
adapter = new FAdapter(context, lists);
lv.setAdapter(adapter);
};
};
Bundle bundle ;TextView tv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
bundle = getArguments();
View view = inflater.inflate(R.layout.fg_style, null);
tv = (TextView) view.findViewById(R.id.tv);
lv = (ListView) view.findViewById(R.id.lv);
lv.setOnItemClickListener(this);
new Thread(){
public void run() {
if(bundle!=null)
{
int i=bundle.getInt("index");
switch(i)
{
case 1:
tv.setText("aaaaaa");
Message msg1 = handler.obtainMessage();
String str1=RequestData.request(path);
msg1.obj = ParserData1.parser(str1);
handler.sendMessage(msg1);
break;
case 2:
Message msg2 = handler.obtainMessage();
tv.setText("bbbbbb");
String str2=RequestData.request(path);
msg2.obj = ParserData1.parser(str2);
handler.sendMessage(msg2);
break;
case 3:
String str3=RequestData.request(path);
tv.setText("cccccc");
Message msg3= handler.obtainMessage();
msg3.obj = ParserData1.parser(str3);
handler.sendMessage(msg3);
break;
default:break;
}
}
};
}.start();
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
}
</span>
fragment用布局文件:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="28sp"/>
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</span>
ListView自定义适配器逻辑代码文件:
<span style="font-size:18px;">package com.example.day20_viewpage2.adapter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.day20_viewpage2.R;
import com.example.day20_viewpage2.utils.AsyncTaskPic;
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;
public class FAdapter extends BaseAdapter{
Context context;
List<Map<String,Object>> list;
//缓存图片
Map<String,Bitmap> imgCache=new HashMap<String, Bitmap>();
public FAdapter(Context context, List<Map<String, Object>> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder=null;
if(view==null)
{
view=LayoutInflater.from(context).inflate(R.layout.fg_item, null);
holder=new ViewHolder();
holder.iv=(ImageView) view.findViewById(R.id.iv);
holder.title=(TextView) view.findViewById(R.id.title);
holder.content=(TextView) view.findViewById(R.id.content);
view.setTag(holder);
}
else
{
holder=(ViewHolder) view.getTag();
}
String title=list.get(position).get("title").toString();
String content=list.get(position).get("content").toString();
holder.title.setText(title);
holder.content.setText(content);
String imgPath=list.get(position).get("imgPath").toString();
//为解决图片移位设默认图片
holder.iv.setImageResource(R.drawable.ic_launcher);
holder.iv.setTag(imgPath);
//若图片缓存区不存在图片地址去下载
if(!imgCache.containsKey(imgPath))
{
AsyncTaskPic taskPic=new AsyncTaskPic(context, holder.iv,imgCache);
taskPic.execute(imgPath);
}
else
{
//图片缓存区中地址(键)对应的图片取出来放在iv上
holder.iv.setImageBitmap(imgCache.get(imgPath));
}
return view;
}
class ViewHolder
{
ImageView iv;
TextView title;
TextView content;
}
}
</span>
ListView自定义适配器用的布局文件:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#0000ff"/>
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#00ff00"/>
</LinearLayout>
</LinearLayout>
</span>
请求网络工具类:
<pre name="code" class="java"><span style="font-size:18px;">package com.example.day20_viewpage2.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class RequestData {
public static String request(String path)
{
ByteArrayOutputStream bo=new ByteArrayOutputStream();
try
{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.connect();
if(con.getResponseCode()==200)
{
InputStream in = con.getInputStream();
int count=0;
byte b[]=new byte[1024];
while((count=in.read(b))!=-1)
{
bo.write(b, 0, count);
bo.flush();
}
}
return bo.toString();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static byte[] getPic(String path)
{
ByteArrayOutputStream bo=new ByteArrayOutputStream();
try
{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.connect();
if(con.getResponseCode()==200)
{
InputStream in = con.getInputStream();
byte b[]=new byte[1024];
int count=0;
while((count=in.read(b))!=-1)
{
bo.write(b,0,count);
bo.flush();
}
}
return bo.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}</span>
解析数据工具类:
<span style="font-size:18px;">package com.example.day20_viewpage2.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 ParserData1 {
static String img="http://litchiapi.jstv.com";
public static List<Map<String,Object>> parser(String data)
{
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try
{
JSONObject jo=new JSONObject(data);
JSONObject jo2=jo.getJSONObject("paramz");
JSONArray ja= jo2.getJSONArray("feeds");
for (int i = 0; i < ja.length(); i++) {
Map<String,Object> map=new HashMap<String, Object>();
JSONObject text = ja.getJSONObject(i);
JSONObject ja2 = text.getJSONObject("data");
String title = ja2.getString("subject");
String content=ja2.getString("summary");
String uri=ja2.getString("cover");
map.put("title", title);
map.put("content", content);
map.put("imgPath", img+uri);
list.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return list;
}
}
</span>
加载图片异步任务类:
<span style="font-size:18px;">package com.example.day20_viewpage2.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 AsyncTaskPic extends AsyncTask<String, Void, Bitmap>{
Context context;
ImageView iv;
Map<String,Bitmap> imgCache;
String imgUri;
public AsyncTaskPic(Context context, ImageView iv,Map<String,Bitmap> imgCache) {
super();
this.context = context;
this.iv = iv;
this.imgCache=imgCache;
}
@Override
protected Bitmap doInBackground(String... params) {
imgUri=params[0];
byte b[]=RequestData.getPic(params[0]);
Bitmap bm = null;
if(b!=null&&b.length>0)
{
bm=BitmapFactory.decodeByteArray(b, 0, b.length);
}
return bm;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//将下载的图片和地址分别作为值和键存在缓存区
imgCache.put(imgUri, result);
if(imgUri.equals(iv.getTag()))
{
iv.setImageBitmap(result);
}
}
}
</span>
二。
此导航栏是ActionBar实现的
主逻辑代码文件:
<span style="font-size:18px;">package com.example.day20;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
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;
@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements TabListener {
private ViewPager viewpager;
private List<Fragment> list;
private ActionBar actionBar;
private static final String path1="http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
private static final String path2="http://litchiapi.jstv.com/api/GetFeeds?column=1&PageSize=10&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
private static final String path3="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);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("新闻").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("娱乐").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("军事").setTabListener(this));
initFragment();
viewpager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager()));
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
actionBar.setSelectedNavigationItem(arg0);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public void initFragment(){
list = new ArrayList<Fragment>();
MyFragment fragment1 = new MyFragment(MainActivity.this,path1);
Bundle bundle = new Bundle();
bundle.putInt("index", 1);
fragment1.setArguments(bundle);
MyFragment fragment2 = new MyFragment(MainActivity.this,path2);
bundle = new Bundle();
bundle.putInt("index", 2);
fragment2.setArguments(bundle);
MyFragment fragment3 = new MyFragment(MainActivity.this,path3);
bundle = new Bundle();
bundle.putInt("index", 3);
fragment3.setArguments(bundle);
list.add(fragment1);
list.add(fragment2);
list.add(fragment3);
}
public class MyFragmentAdapter extends FragmentPagerAdapter{
public MyFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return list.get(arg0);
}
@Override
public int getCount() {
return list.size();
}
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewpager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
</span>
主布局文件:
<span style="font-size:18px;"><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" >
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</span>
fragment逻辑代码文件:
<span style="font-size:18px;">package com.example.day20;
import java.util.List;
import java.util.Map;
import com.example.day20_viewpage2.adapter.FAdapter;
import com.example.day20_viewpage2.utils.ParserData1;
import com.example.day20_viewpage2.utils.RequestData;
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;
import android.widget.TextView;
@SuppressLint("ValidFragment") public class MyFragment extends Fragment{
private TextView tv;
Context context;
String path;
ListView lv;
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
List<Map<String,Object>> Lists=(List<Map<String, Object>>) msg.obj;
FAdapter adapter=new FAdapter(context, Lists);
lv.setAdapter(adapter);
};
};
@SuppressLint("ValidFragment")
public MyFragment(Context context,String path)
{
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);
tv = (TextView) view.findViewById(R.id.tv);
lv=(ListView) view.findViewById(R.id.lv);
if(bundle!=null){
final int tab = bundle.getInt("index");
switch(tab)
{
case 1:
tv.setText("aaaaaa");
break;
case 2:
tv.setText("bbbbb");
break;
case 3:
tv.setText("ccccc");
break;
default:
break;
}
new Thread(){
public void run() {
String str1=RequestData.request(path);
List<Map<String,Object>> list1=ParserData1.parser(str1);
Message msg1=Message.obtain();
msg1.obj=list1;
handler.sendMessage(msg1);
};
}.start();
}
return view;
}
}
</span>
fragment用的布局文件:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="28sp"/>
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout></span>
ListView自定义适配器类:
<span style="font-size:18px;">package com.example.day20_viewpage2.adapter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.day20.R;
import com.example.day20_viewpage2.utils.AsyncTaskPic;
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;
public class FAdapter extends BaseAdapter{
Context context;
List<Map<String,Object>> list;
//缓存图片
Map<String,Bitmap> imgCache=new HashMap<String, Bitmap>();
public FAdapter(Context context, List<Map<String, Object>> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder=null;
if(view==null)
{
view=LayoutInflater.from(context).inflate(R.layout.fg_item, null);
holder=new ViewHolder();
holder.iv=(ImageView) view.findViewById(R.id.iv);
holder.title=(TextView) view.findViewById(R.id.title);
holder.content=(TextView) view.findViewById(R.id.content);
view.setTag(holder);
}
else
{
holder=(ViewHolder) view.getTag();
}
String title=list.get(position).get("title").toString();
String content=list.get(position).get("content").toString();
holder.title.setText(title);
holder.content.setText(content);
String imgPath=list.get(position).get("imgPath").toString();
//为解决图片移位设默认图片
holder.iv.setImageResource(R.drawable.ic_launcher);
holder.iv.setTag(imgPath);
//若图片缓存区不存在图片地址去下载
if(!imgCache.containsKey(imgPath))
{
AsyncTaskPic taskPic=new AsyncTaskPic(context, holder.iv,imgCache);
taskPic.execute(imgPath);
}
else
{
//图片缓存区中地址(键)对应的图片取出来放在iv上
holder.iv.setImageBitmap(imgCache.get(imgPath));
}
return view;
}
class ViewHolder
{
ImageView iv;
TextView title;
TextView content;
}
}
</span>
ListView自定义适配器使用的布局文件:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#0000ff"/>
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#00ff00"/>
</LinearLayout>
</LinearLayout>
</span>
请求网络工具类:
<span style="font-size:18px;">package com.example.day20_viewpage2.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class RequestData {
public static String request(String path)
{
ByteArrayOutputStream bo=new ByteArrayOutputStream();
try
{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.connect();
if(con.getResponseCode()==200)
{
InputStream in = con.getInputStream();
int count=0;
byte b[]=new byte[1024];
while((count=in.read(b))!=-1)
{
bo.write(b, 0, count);
bo.flush();
}
}
return bo.toString();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static byte[] getPic(String path)
{
ByteArrayOutputStream bo=new ByteArrayOutputStream();
try
{
URL url=new URL(path);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.connect();
if(con.getResponseCode()==200)
{
InputStream in = con.getInputStream();
byte b[]=new byte[1024];
int count=0;
while((count=in.read(b))!=-1)
{
bo.write(b,0,count);
bo.flush();
}
}
return bo.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
</span>
解析数据工具类:
<span style="font-size:18px;">package com.example.day20_viewpage2.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 ParserData1 {
static String img="http://litchiapi.jstv.com";
public static List<Map<String,Object>> parser(String data)
{
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try
{
JSONObject jo=new JSONObject(data);
JSONObject jo2=jo.getJSONObject("paramz");
JSONArray ja= jo2.getJSONArray("feeds");
for (int i = 0; i < ja.length(); i++) {
Map<String,Object> map=new HashMap<String, Object>();
JSONObject text = ja.getJSONObject(i);
JSONObject ja2 = text.getJSONObject("data");
String title = ja2.getString("subject");
String content=ja2.getString("summary");
String uri=ja2.getString("cover");
map.put("title", title);
map.put("content", content);
map.put("imgPath", img+uri);
list.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return list;
}
}
</span>
加载图片异步任务类:
<span style="font-size:18px;">package com.example.day20_viewpage2.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 AsyncTaskPic extends AsyncTask<String, Void, Bitmap>{
Context context;
ImageView iv;
Map<String,Bitmap> imgCache;
String imgUri;
public AsyncTaskPic(Context context, ImageView iv,Map<String,Bitmap> imgCache) {
super();
this.context = context;
this.iv = iv;
this.imgCache=imgCache;
}
@Override
protected Bitmap doInBackground(String... params) {
imgUri=params[0];
byte b[]=RequestData.getPic(params[0]);
Bitmap bm = null;
if(b!=null&&b.length>0)
{
bm=BitmapFactory.decodeByteArray(b, 0, b.length);
}
return bm;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//将下载的图片和地址分别作为值和键存在缓存区
imgCache.put(imgUri, result);
if(imgUri.equals(iv.getTag()))
{
iv.setImageBitmap(result);
}
}
}
</span>