側滑+fragment切換頁面+fragment巢狀+二次取樣+輪播圖+gridview展示圖片+網路請求資料+資料庫
全域性配置Appliction
所需要的依賴有:implementation ‘com.google.code.gson:gson:2.8.5’
implementation ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’
implementation ‘com.android.support:design:28.0.0’
implementation project(’:library’)
package com.example.week_03_02; import android.app.Application; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class App extends Application { @Override public void onCreate() { super.onCreate(); ImageLoader.getInstance().init( new ImageLoaderConfiguration.Builder(this) .diskCacheSize(50*1024*1024) .memoryCacheSizePercentage(10) .defaultDisplayImageOptions( new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .showImageOnFail(R.mipmap.ic_launcher) .showImageOnLoading(R.mipmap.ic_launcher) .showImageForEmptyUri(R.mipmap.ic_launcher) .build() ) .build() ); } }
Activity基類`
package com.example.week_03_02; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public abstract class BaseActivty extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResId()); //初始化 initView(savedInstanceState); //新增資料 initData(); } protected abstract void initData(); protected abstract void initView(Bundle savedInstanceState); protected abstract int getLayoutResId(); }
Activity:首頁展示切換頁面的fragment+側滑ddrawerLayout
package com.example.week_03_02; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.MenuItem; import com.example.adapter.HomePageAdapter; import com.example.feagment.LeftFragment; public class MainActivity extends BaseActivty { private DrawerLayout drawerLayout; private TabLayout tabLayout; private ViewPager viewPager; private ActionBarDrawerToggle toggle; @Override protected void initData() { } @Override protected void initView(Bundle savedInstanceState) { drawerLayout=findViewById(R.id.drawerlayout); tabLayout=findViewById(R.id.tablayout); viewPager=findViewById(R.id.viewpager); //繫結介面卡 viewPager.setAdapter(new HomePageAdapter(getSupportFragmentManager())); //tablayout繫結fragment tabLayout.setupWithViewPager(viewPager); //允許側拉左上角按鈕 getSupportActionBar().setDisplayHomeAsUpEnabled(true); toggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close); toggle.syncState(); drawerLayout.addDrawerListener(toggle); //建立側滑介面 if (savedInstanceState==null){ getSupportFragmentManager().beginTransaction() .add(R.id.framelayout,new LeftFragment()) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (toggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } @Override protected int getLayoutResId() { return R.layout.activity_main; } //切換頁面的方法 public void showPage(int position){ viewPager.setCurrentItem(position); drawerLayout.closeDrawer(Gravity.START); } }
對應的切換頁面的介面卡HomePageAdapter
package com.example.adapter;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.feagment.HomeFragment;
import com.example.feagment.MyFragment;
import com.example.feagment.VideoFragment;
public class HomePageAdapter extends FragmentPagerAdapter {
private String[] meuns = new String[]{"首頁","視訊","我的"};
public HomePageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new HomeFragment();
case 1:
return new VideoFragment();
case 2:
return new MyFragment();
}
return null;
}
@Override
public int getCount() {
return meuns.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return meuns[position];
}
}
activity所對應的佈局activity_main佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:id="@+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
//主介面
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/tablayout"/>
<!--支援taglayout滑動的屬性:app:tabMode="scrollable"-->
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:tabSelectedTextColor="#f00"
app:tabTextColor="#ccc"
app:tabBackground="@color/colorPrimary"
app:tabIndicatorColor="@android:color/transparent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@id/viewpager"/>
</android.support.constraint.ConstraintLayout>
<!--側拉介面-->
<FrameLayout
android:id="@+id/framelayout"
android:layout_width="200dp"
android:layout_height="match_parent"
android:background="#fff"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
Fragment所對應的基類BaseFragment
package com.example.feagment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public abstract class BaseFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (getLayoutResId()!=0) {
return inflater.inflate(getLayoutResId(), container, false);
}
View view = getLayoutView();
if (view!=null){
return view;
}
return null;
}
protected int getLayoutResId() {
return 0;
}
protected View getLayoutView() {
return null;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//初始化
initView(view);
//新增資料
initData();
}
protected abstract void initData();
protected abstract void initView(View view);
}
側滑對應的LeftFragment:其中有listview多條目展示圖片和文字,以及圖片的二次取樣展示頭像圖片
package com.example.feagment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;
import com.example.adapter.LeftBaseAdapter;
import com.example.utils.NetUtils;
import com.example.week_03_02.MainActivity;
import com.example.week_03_02.R;
public class LeftFragment extends BaseFragment{
private ListView listView;
private LeftBaseAdapter leftBaseAdapter;
private final int REQUEST_SECCESS=100;
@Override
protected void initData() {
}
@Override
protected void initView(View view) {
//獲取資源id
listView=view.findViewById(R.id.listview);
//建立介面卡
leftBaseAdapter = new LeftBaseAdapter(getActivity());
listView.setAdapter(leftBaseAdapter);
//listview點選事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
//開啟系統相簿
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_SECCESS);
}else{
//呼叫MainActivity中切換頁面的方法
((MainActivity)getActivity()).showPage(position-1);
}
}
});
}
//獲取圖片路徑
private String url2Path(Uri uri){
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), uri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int columnIndexOrThrow = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(columnIndexOrThrow);
}
//獲取二次取樣的圖片
private void progressImage(String imageurl){
int size = getResources().getDimensionPixelSize(R.dimen.leftIconSize);
NetUtils.getInsanner().getBitmap(imageurl, size, size, new NetUtils.ImageCallBack() {
@Override
public void onseccess(Bitmap bitmap) {
leftBaseAdapter.setIconBitmap(bitmap);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_SECCESS&&resultCode==getActivity().RESULT_OK){
Uri uri =data.getData();
//呼叫獲取圖片的方法
progressImage(url2Path(uri));
}
}
@Override
protected int getLayoutResId() {
return R.layout.letr_fragment_item;
}
}
側滑對應的介面卡LeftBaseAdapter
package com.example.adapter;
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 com.example.week_03_02.R;
public class LeftBaseAdapter extends BaseAdapter {
private static final int COUNT_ITEM = 2;
private static final int IMAGE_ITEM = 0;
private static final int TEXT_ITEM = 1;
private String[] meuns = new String[]{"首頁","視訊","我的"};
private Context context;
private Bitmap bitmap;
public LeftBaseAdapter(Context context) {
this.context = context;
}
//傳遞圖片的方法
public void setIconBitmap(Bitmap bitmap){
this.bitmap=bitmap;
notifyDataSetChanged();
}
@Override
public int getViewTypeCount() {
return COUNT_ITEM;
}
@Override
public int getItemViewType(int position) {
return position==0?IMAGE_ITEM:TEXT_ITEM;
}
@Override
public int getCount() {
return meuns.length+1;
}
@Override
public String getItem(int position) {
return meuns[position-1];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(context).inflate(
getItemViewType(position)==IMAGE_ITEM? R.layout.image_item:R.layout.text_item
,parent,false);
holder=new ViewHolder(convertView);
}else{
holder= (ViewHolder) convertView.getTag();
}
//賦值
if (getItemViewType(position)==TEXT_ITEM){
holder.bindText(getItem(position));
}else{
if (bitmap!=null) {
holder.bindIcoe(bitmap);
}
}
return convertView;
}
class ViewHolder{
TextView left_text;
ImageView left_image;
public ViewHolder(View convertView) {
left_text=convertView.findViewById(R.id.left_text);
left_image=convertView.findViewById(R.id.left_image);
convertView.setTag(this);
}
//文字賦值
public void bindText(String item) {
left_text.setText(item);
}
//圖片賦值
public void bindIcoe(Bitmap bitmap) {
left_image.setImageBitmap(bitmap);
}
}
}
側滑所對應的佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ListView
android:id="@+id/listview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
側滑對應的子佈局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10dp">
<ImageView
android:id="@+id/left_image"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintLeft_toRightOf="parent"
app:layout_constraintRight_toLeftOf="parent"
android:src="@mipmap/ic_launcher"/>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="16dp">
<TextView
android:id="@+id/left_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
Activity主介面展示三個頁面Fragment第一個HomeFragment:請求網路資料,多條目展示輪播圖以及網路請求的資料,以及資料的上拉載入下拉重新整理
package com.example.feagment;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.example.adapter.HomeBaseAdapter;
import com.example.bean.BannerBean;
import com.example.utils.NetUtils;
import com.example.week_03_02.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class HomeFragment extends BaseFragment{
private PullToRefreshListView home_listview;
private String url="http://api.expoon.com/AppNews/getNewsList/type/1/p/%d";
private HomeBaseAdapter homeBaseAdapter;
private int mpage=1;
@Override
protected void initData() {
if (mpage==1){
loadBanner();
loadData();
}else{
loadData();
}
}
private void loadData() {
NetUtils.getInsanner().getRequery(String.format(url, mpage), BannerBean.class, new NetUtils.CallBack<BannerBean>() {
@Override
public void onsucess(BannerBean o) {
if (!NetUtils.getInsanner().isNetWork(getActivity())){
Toast.makeText(getActivity(),"當前無網路",Toast.LENGTH_SHORT).show();
}else {
if (o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
home_listview.onRefreshComplete();
return;
}
if (mpage==1){
homeBaseAdapter.setData(o.getData());
}else{
homeBaseAdapter.addData(o.getData());
}
mpage++;
home_listview.onRefreshComplete();
}
}
});
}
private void loadBanner() {
NetUtils.getInsanner().getRequery(String.format(url, mpage), BannerBean.class, new NetUtils.CallBack<BannerBean>() {
@Override
public void onsucess(BannerBean o) {
if (!NetUtils.getInsanner().isNetWork(getActivity())){
Toast.makeText(getActivity(),"當前無網路",Toast.LENGTH_SHORT).show();
}else {
if (o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
home_listview.onRefreshComplete();
return;
}
homeBaseAdapter.setbanner(o.getData());
home_listview.onRefreshComplete();
}
}
});
}
@Override
protected void initView(View view) {
//獲取資源id
home_listview=view.findViewById(R.id.home_listview);
//建立介面卡
homeBaseAdapter = new HomeBaseAdapter(getActivity());
home_listview.setAdapter(homeBaseAdapter);
//設定重新整理模式
home_listview.setMode(PullToRefreshBase.Mode.BOTH);
//重新整理監聽
home_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mpage=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
initData();
}
@Override
protected int getLayoutResId() {
return R.layout.home_item;
}
}
對應的主佈局home_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/home_listview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
對應的多條目展示資料的介面卡HomeBaseAdapter
package com.example.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.bean.BannerBean;
import com.example.week_03_02.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class HomeBaseAdapter extends BaseAdapter {
private static final int COUNT_ITEM = 2;
private static final int BANER_ITEM =0 ;
private static final int DATA_ITEM = 1;
private List<BannerBean.DataBean> mBanner;
private List<BannerBean.DataBean> mData;
private Context context;
public HomeBaseAdapter(Context context) {
this.context = context;
mBanner=new ArrayList<>();
mData=new ArrayList<>();
}
//更新banner資料
public void setbanner(List<BannerBean.DataBean> data){
mBanner.clear();
if (data!=null){
mBanner.addAll(data);
}
notifyDataSetChanged();
}
//下拉重新整理
public void setData(List<BannerBean.DataBean> data){
mData.clear();
if (data!=null){
mData.addAll(data);
}
notifyDataSetChanged();
}
//上拉載入
public void addData(List<BannerBean.DataBean> data){
if (data!=null){
mData.addAll(data);
}
notifyDataSetChanged();
}
@Override
public int getViewTypeCount() {
return COUNT_ITEM;
}
@Override
public int getItemViewType(int position) {
return position==0&&hasBanner()?BANER_ITEM:DATA_ITEM;
}
//判斷banner是否存在
private boolean hasBanner(){
return mBanner.size()>0;
}
@Override
public int getCount() {
return mData.size()+(hasBanner()?1:0);
}
@Override
public BannerBean.DataBean getItem(int position) {
return mData.get(hasBanner()?position-1:position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position)==BANER_ITEM){
BannerViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.benner_item,parent,false);
holder=new BannerViewHolder(convertView);
}else{
holder= (BannerViewHolder) convertView.getTag();
}
holder.bindBanner(mBanner);
}else{
DataViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.data_item,parent,false);
holder=new DataViewHolder(convertView);
}else{
holder= (DataViewHolder) convertView.getTag();
}
holder.bindData(getItem(position));
}
return convertView;
}
//暫存器
class BannerViewHolder{
ViewPager viewPager;
TextView banner_text;
LinearLayout linearLayout;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
//設定viewpager展示位置
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
//執行handle
handler.sendEmptyMessageDelayed(0,2000);
}
};
public BannerViewHolder(View convertView) {
viewPager=convertView.findViewById(R.id.banner_viewpager);
banner_text=convertView.findViewById(R.id.banner_text);
linearLayout=convertView.findViewById(R.id.linearlayout);
convertView.setTag(this);
}
public void bindBanner(final List<BannerBean.DataBean> mBanner) {
//建立介面卡
BannerPageAdapter bannerPageAdapter = new BannerPageAdapter(mBanner, context);
viewPager.setAdapter(bannerPageAdapter);
//監聽
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int index=-1;
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
//給變檔案
banner_text.setText(mBanner.get(i%mBanner.size()).getNews_title());
//改變當前點
linearLayout.getChildAt(i%linearLayout.getChildCount()).setSelected(true);
//還原原來的點
if(index>=0){
linearLayout.getChildAt(index%linearLayout.getChildCount()).setSelected(false);
}
index=i;
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
//初始化小圓點位置
initDot(mBanner.size());
//viewpager預設展示頁面
int count = bannerPageAdapter.getCount()/2;
count=count-count%mBanner.size();
viewPager.setCurrentItem(count);
//開啟輪播
startlooper();
}
//開啟輪播
private void startlooper() {
handler.removeMessages(0);
handler.sendEmptyMessageDelayed(0,2000);
}
//初始化小圓點位置
private void initDot(int size) {
linearLayout.removeAllViews();
for (int i=0;i<size;i++){
ImageView imageView = new ImageView(context);
imageView.setBackgroundResource(R.drawable.selector);
//佈局引數: 寬高包裹 左右8dp
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics());
params.leftMargin=margin;
params.rightMargin=margin;
linearLayout.addView(imageView,params);
}
}
}
class DataViewHolder{
TextView news_id,news_title,news_summary;
ImageView imageView;
public DataViewHolder(View convertView) {
news_id=convertView.findViewById(R.id.news_id);
news_title=convertView.findViewById(R.id.news_title);
news_summary=convertView.findViewById(R.id.news_summary);
imageView=convertView.findViewById(R.id.data_image);
convertView.setTag(this);
}
public void bindData(BannerBean.DataBean item) {
news_id.setText(item.getNews_id());
news_title.setText(item.getNews_title());
news_summary.setText(item.getNews_summary());
ImageLoader.getInstance().displayImage(item.getPic_url(),imageView);
}
}
}
對應的子佈局benner_item(輪播圖佈局)和data_item(資料佈局)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v4.view.ViewPager
android:id="@+id/banner_viewpager"
android:layout_width="0dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintLeft_toRightOf="@id/banner_text"
app:layout_constraintRight_toRightOf="@id/banner_viewpager"
app:layout_constraintBottom_toBottomOf="@id/banner_viewpager"
android:orientation="horizontal"
android:padding="8dp"
/>
<TextView
android:id="@+id/banner_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="@id/banner_viewpager"
app:layout_constraintLeft_toLeftOf="@id/banner_viewpager"
app:layout_constraintRight_toLeftOf="@id/linearlayout"
android:maxLines="1"
android:ellipsize="end"
android:textSize="18sp"/>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10dp">
<ImageView
android:id="@+id/data_image"
android:layout_width="160dp"
android:layout_height="120dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/news_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@id/data_image"
app:layout_constraintBottom_toTopOf="@id/news_title"/>
<TextView
android:id="@+id/news_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/news_id"
app:layout_constraintLeft_toRightOf="@id/data_image"
app:layout_constraintBottom_toTopOf="@id/news_summary"/>
<TextView
android:id="@+id/news_summary"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:maxLines="3"
android:ellipsize="end"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/news_title"
app:layout_constraintLeft_toRightOf="@id/data_image"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
輪播圖對應的介面卡BannerPageAdapter
package com.example.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.bean.BannerBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class BannerPageAdapter extends PagerAdapter {
private List<BannerBean.DataBean> mBanner;
private Context context;
public BannerPageAdapter(List<BannerBean.DataBean> mBanner, Context context) {
this.mBanner = mBanner;
this.context = context;
}
@Override
public int getCount() {
return 5000;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view==o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
container.addView(imageView);
ImageLoader.getInstance().displayImage(mBanner.get(position%mBanner.size()).getPic_url(),imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
對應的bean類
package com.example.bean;
import android.content.Context;
import java.util.List;
public class BannerBean {
private int status;
private String info;
private List<DataBean> data;
public boolean isSuccess(){
return status==1;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String news_id;
private String news_title;
private String news_summary;
private String pic_url;
public String getNews_id() {
return news_id;
}
public void setNews_id(String news_id) {
this.news_id = news_id;
}
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_summary() {
return news_summary;
}
public void setNews_summary(String news_summary) {
this.news_summary = news_summary;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
}
}
第二個fragment:fragment巢狀fragment展示網路請求資料
package com.example.feagment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.example.adapter.VideoPageAdapter;
import com.example.week_03_02.R;
public class VideoFragment extends BaseFragment{
private TabLayout video_tablayout;
private ViewPager video_viewpager;
@Override
protected void initData() {
}
@Override
protected void initView(View view) {
//獲取資源id
video_tablayout=view.findViewById(R.id.video_tablayout);
video_viewpager=view.findViewById(R.id.video_viewpager);
//建立介面卡
video_viewpager.setAdapter(new VideoPageAdapter(getChildFragmentManager()));
video_tablayout.setupWithViewPager(video_viewpager);
}
@Override
protected int getLayoutResId() {
return R.layout.video_item;
}
}
對應的佈局檔案video_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.TabLayout
android:id="@+id/video_tablayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@id/video_viewpager"/>
<android.support.v4.view.ViewPager
android:id="@+id/video_viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/video_tablayout"/>
</android.support.constraint.ConstraintLayout>
對應的介面卡VideoPageAdapter:巢狀fragment
package com.example.adapter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.feagment.VideoSonFragment;
public class VideoPageAdapter extends FragmentPagerAdapter {
private String[] meuns = new String[]{"正在上映","即將上映"};
private String[] urls=new String[]{"http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=10&page=",
"http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?count=10&page="};
public VideoPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
default:
Bundle bundle = new Bundle();
bundle.putString("url",urls[i]);
VideoSonFragment videoSonFragment = new VideoSonFragment();
videoSonFragment.setArguments(bundle);
return videoSonFragment;
}
}
@Override
public int getCount() {
return meuns.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return meuns[position];
}
}
巢狀的fragment佈局樣式相同,所以巢狀的兩個fragment公用一個VideoSonFragment,一個佈局videoson_item
package com.example.feagment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.adapter.VideoBaseAdapter;
import com.example.bean.VideoBean;
import com.example.dao.VideoDao;
import com.example.utils.NetUtils;
import com.example.week_03_02.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class VideoSonFragment extends BaseFragment {
private PullToRefreshListView video_listview;
private VideoBaseAdapter videoBaseAdapter;
private int mpage=1;
private String url;
@Override
protected void initData() {
NetUtils.getInsanner().getRequery(url + mpage, VideoBean.class, new NetUtils.CallBack<VideoBean>() {
@Override
public void onsucess(VideoBean o) {
//請求資料失敗
if (o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
//停止重新整理,載入
video_listview.onRefreshComplete();
return;
}
//判斷是當前第一頁,清空資料庫
if (mpage==1){
VideoDao.getInsanner(getActivity()).deleteAll(url.hashCode());
}
//新增資料到資料庫
VideoDao.getInsanner(getActivity()).addAll(url.hashCode(),o.getResult());
//請求資料成功
if (mpage == 1) {
//查詢資料庫展示資料
videoBaseAdapter.setData(VideoDao.getInsanner(getActivity()).query(url.hashCode()));
//網路請求資料直接展示
//videoBaseAdapter.setData(o.getResult());
} else {
videoBaseAdapter.addData(VideoDao.getInsanner(getActivity()).query(url.hashCode()));
}
//頁面自增
mpage++;
//停止重新整理載入
video_listview.onRefreshComplete();
//載入到最後一頁資料後不再載入
if (o.getResult().size()<10){
video_listview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}else{
video_listview.setMode(PullToRefreshBase.Mode.BOTH);
}
}
});
}
@Override
protected void initView(View view) {
//獲取適配傳來的url
url = getArguments().getString("url");
//獲取資源id
video_listview=view.findViewById(R.id.video_listview);
//建立介面卡
videoBaseAdapter = new VideoBaseAdapter(getActivity());
video_listview.setAdapter(videoBaseAdapter);
video_listview.setMode(PullToRefreshBase.Mode.BOTH);
video_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mpage=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
initData();
//點選條目刪除資料
video_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//呼叫刪除資料庫的方法
VideoDao.getInsanner(getActivity()).delete(url.hashCode(),videoBaseAdapter.getItem(position).getId());
//呼叫介面卡裡刪除集合資料的方法
videoBaseAdapter.del(position);
}
});
//長按點選事件
/* video_listview.getRefreshableView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return true;
}
});*/
}
@Override
protected int getLayoutResId() {
return R.layout.videoson_item;
}
}
佈局videoson_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/video_listview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
巢狀fragment對應的介面卡VideoBaseAdapter
package com.example.adapter;
import android.content.Context;
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 com.example.bean.VideoBean;
import com.example.week_03_02.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class VideoBaseAdapter extends BaseAdapter {
private List<VideoBean.ResultBean> list;
private Context context;
public VideoBaseAdapter(Context context) {
this.context = context;
list=new ArrayList<>();
}
//下拉重新整理
public void setData(List<VideoBean.ResultBean> data){
list.clear();
if (data!=null){
list.addAll(data);
}
notifyDataSetChanged();
}
//上拉載入
public void addData(List<VideoBean.ResultBean> data){
if (data!=null){
list.addAll(data);
}
notifyDataSetChanged();
}
//刪除
public void del(int position){
list.remove(position-1);
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public VideoBean.ResultBean getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.son_item,parent,false);
holder=new ViewHolder(convertView);
}else{
holder= (ViewHolder) convertView.getTag();
}
holder.bindData(getItem(position));
return convertView;
}
class ViewHolder{
TextView name,summary;
ImageView imageView;
public ViewHolder(View convertView) {
name=convertView.findViewById(R.id.name);
summary=convertView.findViewById(R.id.summary);
imageView=convertView.findViewById(R.id.son_image);
convertView.setTag(this);
}
public void bindData(VideoBean.ResultBean item) {
name.setText(item.getName());
summary.setText(item.getSummary());
if (imageView!=null){
ImageLoader.getInstance().displayImage(item.getImageUrl(),imageView);
}
}
}
}
巢狀對應的子佈局son_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10dp">
<ImageView
android:id="@+id/son_image"
android:layout_width="120dp"
android:layout_height="160dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@id/son_image"
app:layout_constraintBottom_toTopOf="@id/summary"/>
<TextView
android:id="@+id/summary"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="@id/son_image"
app:layout_constraintTop_toBottomOf="@id/name"/>
</android.support.constraint.ConstraintLayout>
對應的bean
package com.example.bean;
import java.util.List;
public class VideoBean {
private String message;
private String status;
private List<ResultBean> result;
public boolean isSuccess(){
return status.equals("0000");
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean {
private boolean followMovie;
private int id;
private String imageUrl;
private String name;
private int rank;
private String summary;
public ResultBean(int id, String imageUrl, String name, String summary) {
this.id = id;
this.imageUrl = imageUrl;
this.name = name;
this.summary = summary;
}
public boolean isFollowMovie() {
return followMovie;
}
public void setFollowMovie(boolean followMovie) {
this.followMovie = followMovie;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
}
簡析出來的資料展示資料庫DataBaseSqlite
package com.example.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlite extends SQLiteOpenHelper {
private static final String name ="video.db";
private static final int version=1;
public DataBaseSqlite( Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table videos(_id integer primary key autoincrement," +
"id integer," +
"name text," +
"summary text," +
"imageUrl text," +
"type integer)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Dao包,增刪改查的方法
package com.example.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.bean.VideoBean;
import com.example.database.DataBaseSqlite;
import java.util.ArrayList;
import java.util.List;
public class VideoDao {
private static VideoDao insanner;
private final SQLiteDatabase sb;
public VideoDao(Context context) {
//建立資料庫
sb = new DataBaseSqlite(context).getReadableDatabase();
}
public static VideoDao getInsanner(Context context) {
if (insanner == null) {
insanner = new VideoDao(context);
}
return insanner;
}
//新增資料
public void addAll(int type, List<VideoBean.ResultBean> result) {
try {
sb.beginTransaction();
for (VideoBean.ResultBean bean : result
) {
//新增到資料庫
add(type, bean);
}
sb.setTransactionSuccessful();
} finally {
sb.endTransaction();
}
}
//新增到資料庫
private void add(int type, VideoBean.ResultBean bean) {
ContentValues values = new ContentValues();
values.put("id", bean.getId());
values.put("name", bean.getName());
values.put("summary", bean.getSummary());
values.put("imageUrl", bean.getImageUrl());
values.put("type", type);
sb.insert("videos", null, values);
}
//清空資料庫
public void deleteAll(int type) {
sb.delete("videos", "type=?", new String[]{String.valueOf(type)});
}
//刪除單條資料
public void delete(int type, int id) {
sb.delete("videos", "type=? and id=?", new String[]{String.valueOf(type), String.valueOf(id)});
}
//查詢所有資料
public List<VideoBean.ResultBean> query(int type) {
List<VideoBean.ResultBean> list = new ArrayList<>();
Cursor cursor = sb.query("videos", null, "type=?", new String[]{String.valueOf(type)}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
list.add(
new VideoBean.ResultBean(
Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))),
cursor.getString(cursor.getColumnIndex("imageUrl")),
cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("summary"))
)
);
}
cursor.close();
}
return list;
}
}
MyFragment:最後一個fragment通過PullToRefreshGridView展示圖片
package com.example.feagment;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
import com.example.adapter.MyPhotoAdapter;
import com.example.bean.PhotoBean;
import com.example.utils.NetUtils;
import com.example.week_03_02.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
public class MyFragment extends BaseFragment{
private PullToRefreshGridView gridView;
private String url="http://api.tianapi.com/meinv/?key=7820faabcf4dc5f64ca166dd57b41a80&num=30";
private MyPhotoAdapter myPhotoAdapter;
private int mpage=1;
@Override
protected void initData() {
NetUtils.getInsanner().getRequery(url, PhotoBean.class, new NetUtils.CallBack<PhotoBean>() {
@Override
public void onsucess(PhotoBean o) {
if(o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
gridView.onRefreshComplete();
return;
}
if (mpage==1){
myPhotoAdapter.setdata(o.getNewslist());
}else{
myPhotoAdapter.adddata(o.getNewslist());
}
mpage++;
gridView.onRefreshComplete();
if (o.getNewslist().size()<10){
gridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}
}
});
}
@Override
protected void initView(View view) {
//獲取資源id
gridView=view.findViewById(R.id.my_gridview);
//建立介面卡
myPhotoAdapter = new MyPhotoAdapter(getActivity());
gridView.setAdapter(myPhotoAdapter);
gridView.setMode(PullToRefreshBase.Mode.BOTH);
gridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
mpage=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
initData();
}
});
initData();
}
@Override
protected int getLayoutResId() {
return R.layout.my_item;
}
}
對應的佈局my_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.handmark.pulltorefresh.library.PullToRefreshGridView
android:id="@+id/my_gridview"
android:layout_width="0dp"
android:layout_height="0dp"
android:numColumns="3"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
對應介面卡MyPhotoAdapter
package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.bean.PhotoBean;
import com.example.week_03_02.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class MyPhotoAdapter extends BaseAdapter {
private List<PhotoBean.NewslistBean> list;
private Context context;
public MyPhotoAdapter(Context context) {
this.context = context;
list=new ArrayList<>();
}
//下拉重新整理
public void setdata(List<PhotoBean.NewslistBean> data){
list.clear();
if (data!=null){
list.addAll(data);
}
notifyDataSetChanged();
}
//上拉載入
public void adddata(List<PhotoBean.NewslistBean> data){
if (data!=null){
list.addAll(data);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public PhotoBean.NewslistBean getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null){
convertView=LayoutInflater.from(context).inflate(R.layout.photo_item,parent,false);
holder=new ViewHolder(convertView);
}else{
holder= (ViewHolder) convertView.getTag();
}
holder.bindData(getItem(position));
return convertView;
}
class ViewHolder{
ImageView imageView;
public ViewHolder(View convertView) {
imageView=convertView.findViewById(R.id.photo_image);
convertView.setTag(this);
}
public void bindData(PhotoBean.NewslistBean item) {
ImageLoader.getInstance().displayImage(item.getPicUrl(),imageView);
}
}
}
對應的子佈局photo_item
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="20dp">
<ImageView
android:id="@+id/photo_image"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
工具類
package com.example.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class NetUtils {
private static NetUtils insanner;
private Gson gson;
public NetUtils() {
gson=new Gson();
}
public static NetUtils getInsanner() {
if (insanner==null){
insanner=new NetUtils();
}
return insanner;
}
//獲取圖片的介面
public interface ImageCallBack{
void onseccess(Bitmap bitmap);
}
@SuppressLint("StaticFieldLeak")
public void getBitmap(String imageurl, final int width, final int height, final ImageCallBack imageCallBack){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return getBitmap(strings[0],width,height);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageCallBack.onseccess(bitmap);
}
}.execute(imageurl);
}
//二次取樣,根據圖片路徑 指定寬高,載入縮放圖片
public Bitmap getBitmap(String imageurl,int width,int height){
//第一次載入寬高資訊
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(imageurl,options);
//根據圖片原始寬高 和請求寬高 計算取樣率
options.inSampleSize=Math.max(options.outWidth/width,options.outHeight/height);
//設定真正載入的圖片
options.inJustDecodeBounds=false;
//第二次載入圖片
return BitmapFactory.decodeFile(imageurl,options);
}
//網路資料介面
public interface CallBack<T>{
void onsucess(T t);
}
//介面回撥
@SuppressLint("StaticFieldLeak")
public void getRequery(String urldata, final Class clazz, final CallBack callBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return ge