首先看一下最终效果
经过分析可知,整个页面布局应该是一个Listview,它的每一个条目item中包含原型头像(采用CircleImageVIew)一个数目可变的GridView和其他,Gridview不可滚动,图片查看可缩放使用photoview,图片切换使用viewpager,思路清晰之后,开始写。。。
导入依赖库:
compile 'com.google.code.gson:gson:2.2.4' compile files('libs/circleimageview.jar') compile files('libs/universal-image-loader-1.9.1.jar')
导入photoview源码https://github.com/chrisbanes/PhotoView
初始化ImageLoader
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); DisplayImageOptions defaultOptions = new DisplayImageOptions .Builder() .showImageForEmptyUri(R.drawable.empty_photo) .showImageOnFail(R.drawable.empty_photo) .cacheInMemory(true) .cacheOnDisc(true) .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration .Builder(getApplicationContext()) .defaultDisplayImageOptions(defaultOptions) .discCacheSize(50 * 1024 * 1024)// .discCacheFileCount(100)//缓存一百张图片 .writeDebugLogs() .build(); ImageLoader.getInstance().init(config); } }清单文件中修改
public class MainActivity extends ListActivity { public static final String TAG = "MainActivity"; private ListAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //开启异步任务去模拟获取数据 new LoderDataTask().execute(); } class LoderDataTask extends AsyncTask, Void, MessageModle> { @Override protected MessageModle doInBackground(Void... params) { Gson gson = new Gson(); MessageModle msg = gson.fromJson(getData(), MessageModle.class); return msg; } @Override protected void onPostExecute(MessageModle result) { mAdapter = new ListAdapter(MainActivity.this, result.list); setListAdapter(mAdapter); } } private String getData() { // 模拟网络获取数据 String json = "{\"code\":200,\"msg\":\"ok\",list:[" + "{\"id\":110,\"avator\":\"http://img0.bdstatic.com/img/image/shouye/leimu/mingxing.jpg\",\"name\":\"赵薇\",\"content\":\"今天不开心!\",\"urls\":[]}," + "{\"id\":111,\"avator\":\"http://image.cnwest.com/attachement/jpg/site1/20110507/001372d8a36f0f2f4c953a.jpg\",\"name\":\"李晨\",\"content\":\"我们\"," + " \"urls\":[\"http://guangdong.sinaimg.cn/2015/0530/U11307P693DT20150530094310.jpg\"]}," + "{\"id\":114,\"avator\":\"http://img.hexun.com/2009-05-01/117287830.jpg\",\"name\":\"小马哥\",\"content\":\"今天淘宝了吗\",\"urls\":[" + "\"http://g.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=ccd33b46d53f8794d7ff4b26e2207fc9/0d338744ebf81a4c0f993437d62a6059242da6a1.jpg\"," + "\"http://f.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=6b62f61bac6eddc422e7b7f309e0c7c0/6159252dd42a2834510deef55ab5c9ea14cebfa1.jpg\"," + "\"http://g.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=e58fb67bc8ea15ce45eee301863b4bce/a5c27d1ed21b0ef4fd6140a0dcc451da80cb3e47.jpg\"," + "\"http://c.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=cdab1512d000baa1be2c44b3772bc82f/91529822720e0cf3855c96050b46f21fbf09aaa1.jpg\"]}," + "{\"id\":112,\"avator\":\"http://img3.yxlady.com/yl/UploadFiles_5361/20150528/20150528050208705.jpg\",\"name\":\"邓超\",\"content\":\"奔跑吧兄弟! 欢迎收看!\",\"urls\":[\"http://upload.cbg.cn/2015/0305/1425518659246.jpg\"," + "\"http://www.people.com.cn/mediafile/pic/20150619/30/4179219540177204330.jpg\"]}," + "{\"id\":113,\"avator\":\"http://img4.imgtn.bdimg.com/it/u=945108765,1070109457&fm=21&gp=0.jpg\",\"name\":\"奥巴马\",\"content\":\"holle\",\"urls\":[\"http://f.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=6b62f61bac6eddc422e7b7f309e0c7c0/6159252dd42a2834510deef55ab5c9ea14cebfa1.jpg\",\"http://g.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=e58fb67bc8ea15ce45eee301863b4bce/a5c27d1ed21b0ef4fd6140a0dcc451da80cb3e47.jpg\",\"http://c.hiphotos.bdimg.com/album/s%3D680%3Bq%3D90/sign=cdab1512d000baa1be2c44b3772bc82f/91529822720e0cf3855c96050b46f21fbf09aaa1.jpg\"]}]}"; return json; } }
bean类
public class MessageModle { public int code; public String msg; public ArrayListlist; @Override public String toString() { return "MyMessage [code=" + code + ", msg=" + msg + ", list=" + list + "]"; } }
public class InfoBean { public int id; public String avator; public String name; public String content; public String time; public String[] urls; }布局文件
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:padding="6dp" >
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="暂无数据" />
public class ListAdapter extends BaseAdapter{ private ArrayListmList; private LayoutInflater mInflater; private Context mContext; public ListAdapter(Context context, ArrayList list) { mInflater = LayoutInflater.from(context); mContext=context; this.mList=list; } @Override public int getCount() { return mList==null?0:mList.size(); } @Override public InfoBean getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return getItem(position).id; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.list_item, null); holder.avator=(ImageView)convertView.findViewById(R.id.avator); holder.name=(TextView)convertView.findViewById(R.id.name); holder.content = (TextView) convertView.findViewById(R.id.content); holder.gridView=(NoScrollGridView)convertView.findViewById(R.id.gridView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final InfoBean bean = getItem(position); //加载网络图片 ImageLoader.getInstance().displayImage(bean.avator, holder.avator); holder.name.setText(bean.name); holder.content.setText(bean.content); if(bean.urls!=null&&bean.urls.length>0){ holder.gridView.setVisibility(View.VISIBLE); holder.gridView.setAdapter(new DynamicGridAdapter(bean.urls, mContext)); holder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { imageBrower(position,bean.urls); } }); }else{ holder.gridView.setVisibility(View.GONE); } return convertView; } private void imageBrower(int position, String[] urls) { Intent intent = new Intent(mContext, ImagePagerActivity.class); // 图片url,为了演示这里使用常量,一般从数据库中或网络中获取 intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls); intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position); mContext.startActivity(intent); } // 优化listview private static class ViewHolder { public TextView name; public ImageView avator; TextView content; NoScrollGridView gridView; } }
DynamicGridAdapter
public class DynamicGridAdapter extends BaseAdapter { private String[] files; private LayoutInflater mLayoutInflater; public DynamicGridAdapter(String[] files, Context context) { this.files = files; mLayoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return files == null ? 0 : files.length; } @Override public String getItem(int position) { return files[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MyGridViewHolder viewHolder; if (convertView == null) { viewHolder = new MyGridViewHolder(); convertView = mLayoutInflater.inflate(R.layout.gridview_item, parent, false); viewHolder.imageView = (ImageView) convertView .findViewById(R.id.album_image); convertView.setTag(viewHolder); } else { viewHolder = (MyGridViewHolder) convertView.getTag(); } String url = getItem(position); if (getCount() == 1) { viewHolder.imageView.setLayoutParams(new android.widget.AbsListView.LayoutParams(300, 250)); } if (getCount() == 2 ||getCount() == 4) { viewHolder.imageView.setLayoutParams(new android.widget.AbsListView.LayoutParams(200, 200)); } ImageLoader.getInstance().displayImage(url, viewHolder.imageView); return convertView; } private static class MyGridViewHolder { ImageView imageView; } }布局文件
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:padding="6dp" >
android:id="@+id/avator"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/empty_photo" />
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/avator"
android:textColor="#576B95"
android:textSize="16sp"
android:text="name" />
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/name"
android:layout_marginLeft="10dp"
android:textSize="12sp"
android:layout_toRightOf="@id/avator"
android:text="content" />
android:id="@+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:layout_below="@id/content"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/avator"
android:horizontalSpacing="1dp"
android:numColumns="3"
android:visibility="gone"
android:verticalSpacing="1dp" />
public class NoScrollGridView extends GridView { public NoScrollGridView(Context context) { super(context); } public NoScrollGridView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = 0; int size = getAdapter().getCount(); if (size == 1) { setNumColumns(1); } if ( size==2 || size == 4 ) { setNumColumns(2); } else { setNumColumns(3); } expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec,expandSpec); } }
public class ImagePagerActivity extends FragmentActivity { private static final String STATE_POSITION = "STATE_POSITION"; public static final String EXTRA_IMAGE_INDEX = "image_index"; public static final String EXTRA_IMAGE_URLS = "image_urls"; private HackyViewPager mPager; private int pagerPosition; private TextView indicator; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_detail_pager); pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0); String[] urls = getIntent().getStringArrayExtra(EXTRA_IMAGE_URLS); mPager = (HackyViewPager) findViewById(R.id.pager); ImagePagerAdapter mAdapter = new ImagePagerAdapter( getSupportFragmentManager(), urls); mPager.setAdapter(mAdapter); indicator = (TextView) findViewById(R.id.indicator); CharSequence text = getString(R.string.viewpager_indicator, 1, mPager .getAdapter().getCount()); indicator.setText(text); // 更新下标 mPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount()); indicator.setText(text); } }); if (savedInstanceState != null) { pagerPosition = savedInstanceState.getInt(STATE_POSITION); } mPager.setCurrentItem(pagerPosition); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(STATE_POSITION, mPager.getCurrentItem()); } private class ImagePagerAdapter extends FragmentStatePagerAdapter { public String[] fileList; public ImagePagerAdapter(FragmentManager fm, String[] fileList) { super(fm); this.fileList = fileList; } @Override public int getCount() { return fileList == null ? 0 : fileList.length; } @Override public Fragment getItem(int position) { String url = fileList[position]; return ImageDetailFragment.newInstance(url); } } }
viewpager
public class HackyViewPager extends ViewPager { private static final String TAG = "HackyViewPager"; public HackyViewPager(Context context) { super(context); } public HackyViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (IllegalArgumentException e) { return false; }catch(ArrayIndexOutOfBoundsException e ){ return false; } } }布局文件
xml version="1.0" encoding="utf-8"?>xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" /> android:id="@+id/indicator" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:gravity="center" android:textSize="18sp" android:textColor="@android:color/white" android:text="@string/viewpager_indicator" android:background="@android:color/transparent" />
public class ImageDetailFragment extends Fragment { private String mImageUrl; private ImageView mImageView; private ProgressBar progressBar; private PhotoViewAttacher mAttacher; public static ImageDetailFragment newInstance(String imageUrl) { final ImageDetailFragment f = new ImageDetailFragment(); final Bundle args = new Bundle(); args.putString("url", imageUrl); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageUrl = getArguments() != null ? getArguments().getString("url") : null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.image_detail_fragment, container, false); mImageView = (ImageView) v.findViewById(R.id.image); mAttacher = new PhotoViewAttacher(mImageView); mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() { //点击图片关闭当前activiy @Override public void onPhotoTap(View arg0, float arg1, float arg2) { getActivity().finish(); } }); progressBar = (ProgressBar) v.findViewById(R.id.loading); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new SimpleImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { progressBar.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { String message = null; switch (failReason.getType()) { case IO_ERROR: message = "下载错误"; break; case DECODING_ERROR: message = "图片无法显示"; break; case NETWORK_DENIED: message = "网络有问题,无法下载"; break; case OUT_OF_MEMORY: message = "图片太大无法显示"; break; case UNKNOWN: message = "未知的错误"; break; } Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { progressBar.setVisibility(View.GONE); mAttacher.update(); } }); } }布局文件
xml version="1.0" encoding="utf-8"?>xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@color/black" android:layout_height="match_parent" > android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:adjustViewBounds="true" android:contentDescription="@string/app_name" android:scaleType="centerCrop" /> android:id="@+id/loading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" />