PullToRefreshListView上拉和下拉+輪播圖多條目+fragment巢狀fragment+二次取樣+側拉點選切換fragment+PullToRefreshGritView圖片展示
阿新 • • 發佈:2018-11-22
側拉
程式碼
1提取的基類
1.1Activity的基類
package com.example.zonghelianxi02.ui.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResId()); //初始化view initView(savedInstanceState); //載入資料 initData(); } protected abstract void initData(); protected abstract void initView(Bundle savedInstanceState); protected abstract int getLayoutResId(); }
1.2.fragment的基類
package com.example.zonghelianxi02.ui.fragment; 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) { return inflater.inflate(getLayoutResId(),container,false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //初始化view initView(view); //載入資料 initData(); } protected abstract void initData(); protected abstract void initView(View view); protected abstract int getLayoutResId(); }
2.MainActivity主頁面 包括點選側拉條目跳到不同的fragment和底部Tablayout和fragment切換
package com.example.zonghelianxi02.ui.activity; 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.zonghelianxi02.R; import com.example.zonghelianxi02.ui.adaper.MainAdaper; import com.example.zonghelianxi02.ui.fragment.LeftFragment; public class MainActivity extends BaseActivity { private DrawerLayout drawerLayout; private ActionBarDrawerToggle toggle; private ViewPager viewPager; @Override protected void initData() { } @Override protected void initView(Bundle savedInstanceState) { //當savedInstanceState為空時 if (savedInstanceState==null){ getSupportFragmentManager().beginTransaction() .add(R.id.left_deawer,new LeftFragment()) .commit(); } //顯示側邊欄 getSupportActionBar().setDisplayHomeAsUpEnabled(true); //獲取資源id drawerLayout = findViewById(R.id.drawer_layout); toggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close); drawerLayout.addDrawerListener(toggle); toggle.syncState(); //獲取資源id viewPager = findViewById(R.id.contenes); viewPager.setAdapter(new MainAdaper(getSupportFragmentManager())); //獲取tablayout的id TabLayout tabLayout = findViewById(R.id.bottom_indicator); tabLayout.setupWithViewPager(viewPager); } //側拉右上角圖示可點選 @Override public boolean onOptionsItemSelected(MenuItem item) { if(toggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } //點選跳轉 public void showPage(int position){ viewPager.setCurrentItem(position); drawerLayout.closeDrawer(Gravity.START); } @Override protected int getLayoutResId() { return R.layout.activity_main; } }
3.主頁面佈局 包括DrawerLayout+TabLayout+ViewPager+FrameLayout側拉的佔位佈局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/drawer_layout"
android:layout_height="match_parent"
tools:context=".ui.activity.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="@+id/bottom_indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:tabIndicatorHeight="1dp"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/colorPrimary"
app:tabIndicatorColor="@android:color/transparent"
/>
<android.support.v4.view.ViewPager
android:id="@+id/contenes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_indicator"
/>
</RelativeLayout>
<FrameLayout
android:id="@+id/left_deawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
4.側拉頁面需要的fragment的佈局
<?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/left_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="@android:color/white"
/>
</android.support.constraint.ConstraintLayout>
5.側拉頁面需要的多條目佈局
5.1側拉頭像佈局
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/left_image"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:src="@mipmap/ic_launcher"
/>
</android.support.constraint.ConstraintLayout>
5.2.側拉文字佈局
<?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">
<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"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:textSize="20dp"
android:text="text"
android:gravity="center"
android:padding="15dp"
/>
</android.support.constraint.ConstraintLayout>
6.側拉頁面的fragment程式碼頁面 包括點選側拉的頭像進行二次取樣換頭像
package com.example.zonghelianxi02.ui.fragment;
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 com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.ui.activity.MainActivity;
import com.example.zonghelianxi02.ui.adaper.MenusAdaper;
import com.example.zonghelianxi02.util.BitmapUtil;
import java.util.ArrayList;
import java.util.List;
import static android.app.Activity.RESULT_OK;
public class LeftFragment extends BaseFragment {
private ListView listView;
private MenusAdaper adaper;
private final int REQUESTCOAD_NUM = 100;
private Uri uri;
@Override
protected void initData() {
List<String> list = new ArrayList<>();
list.add("首頁");
list.add("電影");
list.add("訊息");
list.add("圖片");
adaper.setmDatas(list);
}
@Override
protected void initView(View view) {
//獲取資源id
listView = view.findViewById(R.id.left_list);
//建立介面卡
adaper = new MenusAdaper(getActivity());
listView.setAdapter(adaper);
//點選進行圖片取樣換頭像
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, REQUESTCOAD_NUM);
}else{
((MainActivity)getActivity()).showPage(position-1);
}
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.left_fragment;
}
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 progressImaage(String s) {
int size = getResources().getDimensionPixelSize(R.dimen.leftIconSize);
BitmapUtil.getInstance().selectBitmap(s, size, size, new BitmapUtil.CallBack() {
@Override
public void onBitmap(Bitmap bitmap) {
adaper.setIconBitmap(bitmap);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUESTCOAD_NUM && resultCode == RESULT_OK) {
uri = data.getData();
progressImaage(url2Path(uri));
return;
}
}
}
7.側拉頁面的介面卡
package com.example.zonghelianxi02.ui.adaper;
import android.content.ComponentName;
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.zonghelianxi02.R;
import java.util.ArrayList;
import java.util.List;
public class MenusAdaper extends BaseAdapter {
private List<String> mDatas;
private Context mContext;
private Bitmap iconBitmap;
public MenusAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mDatas = new ArrayList<>();
}
public void setmDatas(List<String> datas){
mDatas.clear();
if(datas!=null){
mDatas.addAll(datas);
}
notifyDataSetChanged();
}
public void setIconBitmap(Bitmap bitmap){
this.iconBitmap = bitmap;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mDatas.size()+1;
}
@Override
public String getItem(int position) {
//減一是因為第一個條目是圖片
//文字條目下標從一開始
return mDatas.get(position-1);
}
@Override
public long getItemId(int position) {
return position;
}
private final int ITEM_COUNT=2;
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
private final int IMAGE_TYPE = 0;
private final int TEXT_ITEM = 1;
@Override
public int getItemViewType(int position) {
if(position==0){
return IMAGE_TYPE;
}else{
return TEXT_ITEM;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(
getItemViewType(position)==IMAGE_TYPE? R.layout.left_item_image:R.layout.left_item_text
,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
if(getItemViewType(position)==IMAGE_TYPE){
if (iconBitmap!=null){
holder.bindIcon(iconBitmap);
}
}else{
holder.bindText(getItem(position));
}
return convertView;
}
class ViewHolder{
ImageView image;
TextView text;
//獲取資源id
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.left_image);
text = convertView.findViewById(R.id.left_text);
convertView.setTag(this);
}
//繫結圖片
public void bindIcon(Bitmap iconBitmap) {
image.setImageBitmap(iconBitmap);
}
//繫結文字
public void bindText(String item) {
text.setText(item);
}
}
}
8.主頁面底部導航的介面卡
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.ui.fragment.HomeFragment;
import com.example.zonghelianxi02.ui.fragment.MessageFragment;
import com.example.zonghelianxi02.ui.fragment.MoveFragment;
import com.example.zonghelianxi02.ui.fragment.PickFragment;
public class MainAdaper extends FragmentPagerAdapter {
private String[] pageName = new String[]{
"首頁","電影","訊息","圖片"
};
public MainAdaper(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new HomeFragment();
case 1:
return new MoveFragment();
case 2:
return new MessageFragment();
case 3:
return new PickFragment();
default:
return new Fragment();
}
}
@Override
public int getCount() {
return pageName.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return pageName[position];
}
}
輪播圖多條目
程式碼
1.佈局頁面
<?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_pull"
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>
2.多條目佈局頁面
2.1.多條目輪播圖佈局頁
<?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.support.v4.view.ViewPager
android:id="@+id/home_page"
android:layout_width="0dp"
android:layout_height="240dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<LinearLayout
android:id="@+id/dot"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintRight_toRightOf="@id/home_page"
app:layout_constraintBottom_toBottomOf="@id/home_page"
android:padding="8dp"
/>
<TextView
android:id="@+id/desc"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="@id/home_page"
app:layout_constraintBottom_toBottomOf="@id/home_page"
app:layout_constraintRight_toLeftOf="@id/dot"
android:maxLines="1"
android:ellipsize="end"
/>
</android.support.constraint.ConstraintLayout>
2.2.多條目文字頁
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/home_image"
android:layout_width="120dp"
android:layout_height="150dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<TextView
android:id="@+id/home_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="@id/home_image"
app:layout_constraintLeft_toRightOf="@id/home_image"
app:layout_constraintRight_toRightOf="parent"
android:text="title"
android:textSize="20dp"
android:maxLines="2"
/>
<TextView
android:id="@+id/home_ctime"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="@id/home_image"
app:layout_constraintLeft_toRightOf="@id/home_image"
app:layout_constraintRight_toRightOf="parent"
android:text="ctime"
android:textSize="20dp"
android:maxLines="2"
/>
</android.support.constraint.ConstraintLayout>
3.邏輯程式碼也
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.HomeBean;
import com.example.zonghelianxi02.ui.adaper.HomeAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class HomeFragment extends BaseFragment {
private PullToRefreshListView refreshListView;
private HomeAdaper adaper;
private String url ="http://api.tianapi.com/military/?key=605fa0a929c8d8b116424df0510c6b2a&num=10";
private int mPage = 1;
@Override
protected void initData() {
if(mPage==1){
loadBunner();
loadData();
}else{
loadData();
}
}
//載入bunner
private void loadBunner() {
NetUtil.getIntance().getRequest(url, HomeBean.class, new NetUtil.CallBack<HomeBean>() {
@Override
public void onSuccess(HomeBean o) {
if(o==null || !o.isSuccess()){
Toast.makeText(getActivity(),"請求錯誤",Toast.LENGTH_SHORT).show();
return;
}
adaper.setmBunner(o.getNewslist());
}
});
}
//載入新聞
private void loadData() {
NetUtil.getIntance().getRequest(url, HomeBean.class, new NetUtil.CallBack<HomeBean>() {
@Override
public void onSuccess(HomeBean o) {
if(o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"請求錯誤",Toast.LENGTH_SHORT).show();
refreshListView.onRefreshComplete();
return;
}
if(mPage==1){
adaper.setmData(o.getNewslist());
}else{
adaper.addmData(o.getNewslist());
}
mPage++;
//停止重新整理和載入
refreshListView.onRefreshComplete();
}
});
}
@Override
protected void initView(View view) {
//獲取資源id
refreshListView = view.findViewById(R.id.home_pull);
//建立介面卡
adaper = new HomeAdaper(getActivity());
refreshListView.setAdapter(adaper);
//設定支援重新整理和載入
refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
//設定監聽
refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//重新整理
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mPage=1;
initData();
}
//載入
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.home_fragment;
}
}
4.介面卡也面
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.R;
import com.example.zonghelianxi02.model.HomeBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class HomeAdaper extends BaseAdapter {
private List<HomeBean.NewslistBean> mData;
private List<HomeBean.NewslistBean> mBunner;
private Context mContext;
public HomeAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
mBunner = new ArrayList<>();
}
//判斷是否有Bunner
public boolean hasBunner(){
return mBunner.size()>0;
}
//重新整理bunner
public void setmBunner(List<HomeBean.NewslistBean> bunner){
mBunner.clear();
if(bunner!=null){
mBunner.addAll(bunner);
}
notifyDataSetChanged();
}
//重新整理新聞
public void setmData(List<HomeBean.NewslistBean> datas){
mData.clear();
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
//追加新聞
public void addmData(List<HomeBean.NewslistBean> datas){
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return hasBunner()?mData.size()+1:mData.size();
}
@Override
public HomeBean.NewslistBean getItem(int position) {
return mData.get(hasBunner()?position-1:position);
}
@Override
public long getItemId(int position) {
return position;
}
private final int ITEM_COUNT = 2;
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
private final int BUNNER_TYPE = 0;
private final int TEXT_TYPE = 1;
@Override
public int getItemViewType(int position) {
return position==0&&hasBunner()?BUNNER_TYPE:TEXT_TYPE;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemViewType(position)==BUNNER_TYPE){
BunnerViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.home_bunner_item,parent,false);
viewHolder = new BunnerViewHolder(convertView);
}else{
viewHolder = (BunnerViewHolder) convertView.getTag();
}
viewHolder.bindBunner(mBunner);
}else{
DataViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.home_text_item,parent,false);
viewHolder = new DataViewHolder(convertView);
}else{
viewHolder = (DataViewHolder) convertView.getTag();
}
viewHolder.bindData(getItem(position));
}
return convertView;
}
//圖片條目的暫存器
class BunnerViewHolder{
ViewPager viewPager;
LinearLayout dot;
TextView desc;
//獲取資源id
public BunnerViewHolder(View convertView) {
viewPager = convertView.findViewById(R.id.home_page);
dot = convertView.findViewById(R.id.dot);
desc = convertView.findViewById(R.id.desc);
convertView.setTag(this);
}
//設定值
public void bindBunner(final List<HomeBean.NewslistBean> mBunner) {
//建立介面卡
BunnerAdaper adaper = new BunnerAdaper(mBunner,mContext);
//設定介面卡
viewPager.setAdapter(adaper);
//滑動監聽
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) {
//改變text文字
desc.setText(mBunner.get(i%mBunner.size()).getTitle());
//改變當前點
dot.getChildAt(i%dot.getChildCount()).setSelected(true);
//還原原來點
if(index>=0){
dot.getChildAt(index%dot.getChildCount()).setSelected(false);
}
index = i;
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
//初始化小圓點
initDot(mBunner.size());
//設定中間位置
int center = adaper.getCount()/2;
center = center - center%mBunner.size();
viewPager.setCurrentItem(center);
startLooper();
}
//建立handler
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
handler.sendEmptyMessageDelayed(0,2000);
}
};
//開始輪播
private void startLooper() {
handler.removeCallbacksAndMessages(null);
handler.sendEmptyMessageDelayed(0,2000);
}
//初始化小圓點
private void initDot(int size) {
dot.removeAllViews();
for (int i = 0; i <size ; i++) {
ImageView imageView = new ImageView(mContext);
imageView.setBackgroundResource(R.drawable.select_dot);
//佈局引數
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
int marage = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,
mContext.getResources().getDisplayMetrics());
params.leftMargin = marage;
params.rightMargin = marage;
dot.addView(imageView,params);
}
}
}
//內容條目暫存器
class DataViewHolder{
ImageView image;
TextView title;
TextView ctime;
//獲取資源id
public DataViewHolder(View convertView) {
image = convertView.findViewById(R.id.home_image);
title = convertView.findViewById(R.id.home_title);
ctime = convertView.findViewById(R.id.home_ctime);
convertView.setTag(this);
}
//設定值
public void bindData(HomeBean.NewslistBean item) {
title.setText(item.getTitle());
ctime.setText(item.getCtime());
ImageLoader.getInstance().displayImage(item.getPicUrl(),image);
}
}
}
5.輪播圖介面卡
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.model.HomeBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class BunnerAdaper extends PagerAdapter {
private List<HomeBean.NewslistBean> mBunner;
private Context mContext;
public BunnerAdaper(List<HomeBean.NewslistBean> mBunner, Context mContext) {
this.mBunner = mBunner;
this.mContext = mContext;
}
@Override
public int getCount() {
return mBunner.size()>0?5000:0;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view==o;
}
public HomeBean.NewslistBean getItem(int position){
return mBunner.get(position%mBunner.size());
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
container.addView(imageView);
ImageLoader.getInstance().displayImage(getItem(position).getPicUrl(),imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
fragment巢狀fragment展示資料
程式碼
1.外部fragment的佈局
<?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/move_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<android.support.v4.view.ViewPager
android:id="@+id/move_pager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/move_layout"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
2.內部fragment展示tablayout的介面卡 展示頭部內容
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.ui.fragment.MoveListFragment;
public class MovePageAdaper extends FragmentPagerAdapter {
private String[] names = new String[]{
"正在上映","即將上映"
};
private String[] url = new String[]{
"http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=%d&page=%d",
"http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?count=%d&page=%d"
};
public MovePageAdaper(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
default:
Bundle bundle = new Bundle();
bundle.putString("url",url[i]);
MoveListFragment moveListFragment = new MoveListFragment();
moveListFragment.setArguments(bundle);
return moveListFragment;
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return names[position];
}
@Override
public int getCount() {
return names.length;
}
}
3.外部fragment邏輯程式碼也
package com.example.zonghelianxi02.ui.fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.ui.adaper.MovePageAdaper;
public class MoveFragment extends BaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void initData() {
}
@Override
protected void initView(View view) {
//獲取資源id
tabLayout = view.findViewById(R.id.move_layout);
viewPager = view.findViewById(R.id.move_pager);
viewPager.setAdapter(new MovePageAdaper(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
@Override
protected int getLayoutResId() {
return R.layout.move_fragment;
}
}
4.內部展示展示內容的fragment佈局
<?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/pull_list"
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>
5.展示內容條目的佈局
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/move_image"
android:layout_width="120dp"
android:layout_height="150dp"
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="@id/move_image"
app:layout_constraintLeft_toRightOf="@id/move_image"
app:layout_constraintRight_toRightOf="parent"
android:maxLines="3"
android:textSize="20sp"
android:text="name"
/>
<TextView
android:id="@+id/summary"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@id/move_image"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="@id/move_image"
android:maxLines="3"
android:textSize="20sp"
android:text="summary"
/>
</android.support.constraint.ConstraintLayout>
6.展示內用的介面卡
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.R;
import com.example.zonghelianxi02.model.MoveBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class MoveListAdaper extends BaseAdapter {
private List<MoveBean.ResultBean> mData;
private Context mContext;
public MoveListAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
}
public void setmData(List<MoveBean.ResultBean> result){
mData.clear();
if(result!=null){
mData.addAll(result);
}
notifyDataSetChanged();
}
public void addmResult(List<MoveBean.ResultBean> result){
if(result!=null){
mData.addAll(result);
}
notifyDataSetChanged();
}
//刪除
public void setDelete(int position){
mData.remove(position-1);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public MoveBean.ResultBean getItem(int position) {
return mData.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(mContext).inflate(R.layout.move_item,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bind(getItem(position));
return convertView;
}
class ViewHolder{
ImageView image;
TextView name;
TextView summary;
View convertView;
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.move_image);
name = convertView.findViewById(R.id.name);
summary = convertView.findViewById(R.id.summary);
convertView.setTag(this);
}
public void bind(MoveBean.ResultBean item) {
name.setText(item.getName());
summary.setText(item.getSummary());
ImageLoader.getInstance().displayImage(item.getImageUrl(),image);
}
}
}
7.內容的fragment頁面 邏輯程式碼頁面
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.db.MoveDao;
import com.example.zonghelianxi02.model.MoveBean;
import com.example.zonghelianxi02.ui.adaper.MoveListAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class MoveListFragment extends BaseFragment {
private PullToRefreshListView refreshListView;
private int mPage = 1;
private String url;
private MoveListAdaper moveListAdaper;
private final int LOAD_COUNT = 10;
//載入資料
@Override
protected void initData() {
NetUtil.getIntance().getRequest(String.format(url,LOAD_COUNT, mPage), MoveBean.class, new NetUtil.CallBack<MoveBean>() {
@Override
public void onSuccess(MoveBean o) {
if(o==null || !o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
//停止重新整理
refreshListView.onRefreshComplete();
return;
}
//資料庫操作
if(mPage == 1){
MoveDao.getIntance(getActivity()).deleteAll(url.hashCode());
}
MoveDao.getIntance(getActivity()).addAll(url.hashCode(),o.getResult());
//重新整理介面卡
if(mPage == 1){
//從資料庫查詢
moveListAdaper.setmData(MoveDao.getIntance(getActivity()).select(url.hashCode()));
//通過解析出來傳到介面卡直接展示
//moveListAdaper.setmData(o.getResult());
}else{
//從資料庫查詢
moveListAdaper.addmResult(MoveDao.getIntance(getActivity()).select(url.hashCode()));
//通過解析出來傳到介面卡直接展示
// moveListAdaper.addmResult(o.getResult());
}
//頁面自增
mPage++;
//停止重新整理/載入
refreshListView.onRefreshComplete();
if(o.getResult().size()<LOAD_COUNT){
refreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}else{
refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
}
}
});
}
//初始化view
@Override
protected void initView(View view) {
//通過fragment把url地址介面傳回來
url = getArguments().getString("url");
//獲取資源id
refreshListView = view.findViewById(R.id.pull_list);
//建立介面卡
moveListAdaper = new MoveListAdaper(getActivity());
//設定介面卡
refreshListView.setAdapter(moveListAdaper);
//設定支援重新整理和載入
refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//重新整理
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mPage=1;
initData();
}
//載入
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
//點選刪除
refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//刪除資料庫
MoveDao.getIntance(getActivity()).delete(url.hashCode(),moveListAdaper.getItem(position).getId());
//刪除頁面
moveListAdaper.setDelete(position);
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.move_list_fragment;
}
}
8.資料庫建立表的 頁面
package com.example.zonghelianxi02.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SqlitHelper extends SQLiteOpenHelper {
public SqlitHelper(Context context) {
super(context, "Move.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table moves(_id integer primary key autoincrement," +
"id integer," +
"name text," +
"summary text," +
"url text," +
"type integer)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
9.資料庫寫增刪改查方法頁面
package com.example.zonghelianxi02.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.zonghelianxi02.model.MoveBean;
import java.util.ArrayList;
import java.util.List;
public class MoveDao {
private static MoveDao intance;
private final SqlitHelper helper;
private final SQLiteDatabase sb;
public MoveDao(Context context) {
//建立資料庫
helper = new SqlitHelper(context);
sb = helper.getWritableDatabase();
}
public static MoveDao getIntance(Context context) {
if (intance == null) {
intance = new MoveDao(context);
}
return intance;
}
//新增
public void add(int type, MoveBean.ResultBean bean) {
ContentValues values = new ContentValues();
values.put("id", bean.getId());
values.put("name", bean.getName());
values.put("summary", bean.getSummary());
values.put("url", bean.getImageUrl());
values.put("type", type);
sb.insert("moves", null, values);
}
public void addAll(int type, List<MoveBean.ResultBean> datas) {
try {
sb.beginTransaction();
for (MoveBean.ResultBean bean : datas) {
add(type, bean);
}
sb.setTransactionSuccessful();
} finally {
sb.endTransaction();
}
}
//刪除
public void delete(int type, int id) {
sb.delete("moves", "id=? and type=?", new String[]{String.valueOf(id), String.valueOf(type)});
}
public void deleteAll(int type) {
sb.delete("moves", "type=?", new String[]{String.valueOf(type)});
}
//查詢
public List<MoveBean.ResultBean> select(int type) {
List<MoveBean.ResultBean> list = new ArrayList<>();
Cursor moves = sb.query("moves", null, "type=?", new String[]{String.valueOf(type)}, null, null, null);
if (moves != null) {
while (moves.moveToNext()) {
String id1 = moves.getString(moves.getColumnIndex("id"));
Integer id = Integer.valueOf(id1);
String url = moves.getString(moves.getColumnIndex("url"));
String name = moves.getString(moves.getColumnIndex("name"));
String summary = moves.getString(moves.getColumnIndex("summary"));
MoveBean.ResultBean bean = new MoveBean.ResultBean(id,url,name,summary);
list.add(bean);
}
moves.close();
}
return list;
}
}
PullToRefreshGridView展示圖片頁面
程式碼
1.佈局頁面
<?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/pick_pull"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:numColumns="auto_fit"
/>
</android.support.constraint.ConstraintLayout>
2.內容條目佈局頁
<?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">
<ImageView
android:id="@+id/pick_image"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
3.內容介面卡頁
package com.example.zonghelianxi02.ui.adaper;
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.zonghelianxi02.R;
import com.example.zonghelianxi02.model.PickBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class PickAdaper extends BaseAdapter {
private List<PickBean.NewslistBean> mData;
private Context mContext;
public PickAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
}
//重新整理
public void setmData(List<PickBean.NewslistBean> datas){
mData.clear();
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
//載入
public void addmData(List<PickBean.NewslistBean> datas){
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public PickBean.NewslistBean getItem(int position) {
return mData.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(mContext).inflate(R.layout.pick_item,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bind(getItem(position));
return convertView;
}
//建立暫存器
class ViewHolder{
ImageView image;
TextView text;
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.pick_image);
convertView.setTag(this);
}
public void bind(PickBean.NewslistBean item) {
ImageLoader.getInstance().displayImage(item.getPicUrl(),image);
}
}
}
4.內容邏輯程式碼也
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.PickBean;
import com.example.zonghelianxi02.ui.adaper.PickAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
public class PickFragment extends BaseFragment {
private PullToRefreshGridView gridView;
private PickAdaper adaper;
private String url = "http://api.tianapi.com/meinv/?key=605fa0a929c8d8b116424df0510c6b2a&num=10";
private int mPage = 1;
private final int LOAD_NUM = 10;
@Override
protected void initData() {
NetUtil.getIntance().getRequest(url, PickBean.class, new NetUtil.CallBack<PickBean>() {
@Override
public void onSuccess(PickBean o) {
if(o==null || !o.isSussecc()){
Toast.makeText(getActivity(),"請求錯誤",Toast.LENGTH_SHORT).show();
gridView.onRefreshComplete();
return;
}
if(mPage == 1){
adaper.setmData(o.getNewslist());
}else{
adaper.addmData(o.getNewslist());
}
mPage++;
gridView.onRefreshComplete();
if(o.getNewslist().size()<LOAD_NUM){
gridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}
}
});
}
@Override
protected void initView(View view) {
//獲取資源id
gridView = view.findViewById(R.id.pick_pull);
//建立介面卡
adaper = new PickAdaper(getActivity());
gridView.setAdapter(adaper);
//設定支援重新整理載入
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();
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.pick_fragment;
}
}
通用
1.Application初始化圖片
package com.example.zonghelianxi02.Application;
import android.app.Application;
import android.graphics.Bitmap;
import com.example.zonghelianxi02.R;
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()
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.showImageOnLoading(R.mipmap.ic_launcher)
.build())
.build());
}
}
2.工具類
package com.example.zonghelianxi02.util;
import android.annotation.SuppressLint;
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 NetUtil {
private static NetUtil intance;
private Gson gson;
public NetUtil() {
gson = new Gson();
}
public static NetUtil getIntance() {
if(intance==null){
intance = new NetUtil();
}
return intance;
}
//執行網路請求返回String
public String getRequest(String urlStr){
String result = "";
try {
//定義url地址
URL url = new URL(urlStr);
//開啟連線
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//設定請求方式
urlConnection.setRequestMethod("GET");
//設定超時
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//獲取請求碼
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){
result = stream2String(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//將位元組流轉換為字元流
private String stream2String(InputStream inputStream) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
for (String tmp = br.readLine();tmp!=null;tmp=br.readLine()){
builder.append(tmp);
}
return builder.toString();
}
//執行網路請求返回bean
public <E> E getRequest(String urlStr,Class clazz){
return (E) gson.fromJson(getRequest(urlStr),clazz);
}
//定義介面
public interface CallBack<E>{
void onSuccess(E e);
}
@SuppressLint("StaticFieldLeak")
public void getRequest(String urlStr, final Class clazz, final CallBack callBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
callBack.onSuccess(o);
}
}.execute(urlStr);
}
}
3.二次取樣工具類
package com.example.zonghelianxi02.util;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class BitmapUtil {
private static BitmapUtil instance;
public BitmapUtil() {
}
public static BitmapUtil getInstance() {
if(instance==null){
instance = new BitmapUtil();
}
return instance;
}
//二次取樣請求
public Bitmap selectBitmap(String imagePath,int width,int height){
//第一次只加載寬高資訊
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath,options);
//根據原始寬高和請求寬高計算取樣lv
options.inSampleSize = Math.max(options.outWidth/width,options.outHeight/height);
//設定真正載入圖片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath,options);
}
//定義介面
public interface CallBack{
void onBitmap(Bitmap bitmap);
}
//回撥請求
@SuppressLint("StaticFieldLeak")
public void selectBitmap(String imagePath, final int width, final int height, final CallBack callBack){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return selectBitmap(strings[0],width,height);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
callBack.onBitmap(bitmap);
}
}.execute(imagePath);
}
}
4.二次取樣在values裡建一個dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="leftIconSize">100dp</dimen>
</resources>
5.輪播圖小圓點
5.1預設圓點
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<size
android:width="8dp"
android:height="8dp"
/>
<solid
android:color="#909090"
/>
</shape>
5.2選中圓點
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<size
android:width="8dp"
android:height="8dp"
/>
<solid
android:color="#900000"
/>
</shape>
5.3select
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_sel_dot" android:state_selected="true"/>
<item android:drawable="@drawable/shape_normal_dot"/>
</selector>
用到的bean類
1首頁bean
package com.example.zonghelianxi02.model;
import java.util.List;
public class HomeBean {
private int code;
private String msg;
private List<NewslistBean> newslist;
private final int SUCCESS_CODE=200;
public boolean isSuccess(){
return SUCCESS_CODE == code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<NewslistBean> getNewslist() {
return newslist;
}
public void setNewslist(List<NewslistBean> newslist) {
this.newslist = newslist;
}
public static class NewslistBean {
private String ctime;
private String title;
private String description;
private String picUrl;
private String url;
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;