簡介
在現在的安卓開發中,大部分需求會經常遇上viewpager和tablayout組合實現的功能,然後通過網絡請求拿到數據然後顯示在頁面上,之前自己也在網上搜索過一些文章,要麼是幫助不大,要麼是效果不一樣,要麼是貼的代碼不完整,從而導致一腦門汗吶,所以我自己在摸索了一陣之後,參考騰訊新聞的首頁,完成了一個大致還算完整的demo,供大家參考。有問題還望大家指正出來,感激不盡。。
老規矩,先貼效果圖
本文先着重顯示viewpager+tablayout;
下面的源碼是整合後的代碼,已經實現了部分新功能。
使用到得控件和工具簡介:
- RefreshLayout(上拉加載下拉刷新控件)
- Adapter(加載數據的適配器)
- ViewPager(視圖加載)
- TabLayout(最上方的title控件)
- Handler(網絡通信)
- Glide(圖片框架)
好了,開始上代碼吧!!!
首先,先導入一系列的插件:
//基本使用
implementation 'com.android.support:design:27.0.2'
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:cardview-v7:27.0.2'
//圖片加載
implementation 'com.github.bumptech.glide:glide:3.7.0'
//刷新加載框架
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.3'
implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.3'
//網絡請求
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
//數據解析
implementation 'com.google.code.gson:gson:2.8.5'
//???
implementation 'com.squareup.picasso:picasso:2.5.2'
當然,請求數據肯定是用到了網絡,就要放入網絡權限:
<uses-permission android:name="android.permission.INTERNET"/>
佈局xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="@+id/frag_two_tabLayout"
android:layout_width="@dimen/dimen_410_dip"
app:tabIndicatorColor="@color/blue"
app:tabTextColor="@color/grey"
app:tabSelectedTextColor="@color/black"
android:layout_height="@dimen/dimen_60_dip"
android:background="@color/cyan"/>
<ImageView
android:id="@+id/frag_two_img_add"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_60_dip"
android:layout_alignParentTop="true"
android:padding="@dimen/dimen_10_dip"
android:background="@color/cyan"
android:layout_toEndOf="@+id/frag_two_tabLayout"
android:src="@android:drawable/ic_menu_add"/>
</RelativeLayout>
<TextView
android:id="@+id/txt_show_toast"
android:background="@color/dodgerblue"
android:textColor="@color/white"
android:textSize="@dimen/dimen_14_dip"
android:text="又爲您找到了10條數據"
android:gravity="center"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_30_dip">
</TextView>
<com.scwang.smartrefresh.layout.SmartRefreshLayout
android:id="@+id/frag_two_refreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srlEnablePreviewInEditMode="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/frag_two_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white" />
<View
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_0.5_dip"
android:background="@color/gainsboro" />
</LinearLayout>
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
</LinearLayout>
MainActivity.class
/**
* 主Activity
* 用來顯示主界面
*/
public class MainActivity extends FragmentActivity implements View.OnClickListener {
//上下文
Activity activity = this;
//當前所在的fragment的值,默認爲0
public static int DEFAULTFRAGMENT = 0;
//控件
static ViewPager viewPager;
TabLayout frag_two_tabLayout;
ImageView frag_two_img_add;
//你是多餘的
TextView txt_show_toast;
//添加頭部item佈局信息
List<String> titles = Arrays.asList("頭條", "社會", "國內", "國際", "娛樂", "體育", "軍事", "科技", "財經", "時尚");
//每一個頭部item所對應一個item
static List<Frag_Two_Frag_Item> frag_two_frag_items = new ArrayList<>();
//適配器
static FragmentPagerAdapter fragmentPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉標題欄
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//加載刷新框架
final RefreshLayout frag_two_refreshLayout = findViewById(R.id.frag_two_refreshLayout);
//越界回彈
frag_two_refreshLayout.setEnableOverScrollBounce(false);
//在刷新或者加載的時候不允許操作視圖
frag_two_refreshLayout.setDisableContentWhenRefresh(true);
frag_two_refreshLayout.setDisableContentWhenLoading(true);
//監聽列表在滾動到底部時觸發加載事件(默認true)
frag_two_refreshLayout.setEnableAutoLoadmore(false);
//設置自定義Header
frag_two_refreshLayout.setHeaderHeight(50);
frag_two_refreshLayout.setRefreshHeader(new ClassicsHeader(activity));
//設置自定義Footer
frag_two_refreshLayout.setFooterHeight(50);
frag_two_refreshLayout.setRefreshFooter(new ClassicsFooter(activity));
/**
* 正在下拉刷新數據中
*/
frag_two_refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
Log.i("activity", "555");
//設置刷新事件爲2s
frag_two_refreshLayout.finishRefresh(2000);
Frag_Two_Frag_Item.adapter.notifyDataSetChanged();
}
});
/**
* 正在上拉加載數據中
*/
frag_two_refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
@Override
public void onLoadmore(RefreshLayout refreshlayout) {
Log.i("activity", "444");
//設置加載事件爲2s
frag_two_refreshLayout.finishLoadmore(2000);
Frag_Two_Frag_Item.adapter.notifyDataSetChanged();
}
});
/**
* sf的事件監聽
*/
frag_two_refreshLayout.setOnMultiPurposeListener(new OnMultiPurposeListener() {
@Override
public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
}
@Override
public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
}
@Override
public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {
}
@Override
public void onHeaderFinish(RefreshHeader header, boolean success) {
}
@Override
public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
}
@Override
public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
}
@Override
public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {
}
@Override
public void onFooterFinish(RefreshFooter footer, boolean success) {
}
@Override
public void onLoadmore(RefreshLayout refreshlayout) {
}
@Override
public void onRefresh(RefreshLayout refreshlayout) {
}
@Override
public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {
Log.i("activity", "" + oldState + "-------" + newState);
if(newState == RefreshState.RefreshFinish){
Log.i("getActivity()", "刷新完成");
txt_show_toast.setVisibility(View.VISIBLE);
}
if(oldState == RefreshState.RefreshFinish){
txt_show_toast.setVisibility(View.GONE);
}
}
});
//修改狀態欄的顏色
StatusBarCompat.setStatusBarColor(activity, ContextCompat.getColor(activity, R.color.cyan));
//初始化view
initView();
//初始化數據
initData();
//通過適配器加載
viewPager.setAdapter(fragmentPagerAdapter);
//設置viewpager的緩存個數,全部頁面都緩存
viewPager.setOffscreenPageLimit(9);
//必須與viewpager綁定,否則效果就看不出來
frag_two_tabLayout.setupWithViewPager(viewPager);
//設置tablayout的屬性
frag_two_tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
frag_two_tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}
/**
* 初始化數據
*/
private void initData() {
//循環加載titles數組內容到fragment(每一個tablayout的顯示界面都是一個frag)
for(String title : titles){
//通過frag對象加載title,並完成實例化
Frag_Two_Frag_Item instance = Frag_Two_Frag_Item.getInstance(title);
frag_two_frag_items.add(instance);
}
//用適配器完成每一個fragment的加載完成
fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
//返回指定的fragment
return frag_two_frag_items.get(position);
}
@Override
public int getCount() {
//fragment的個數
return frag_two_frag_items.size();
}
@Override
public CharSequence getPageTitle(int position) {
//將titles的內容加載進每一個(position爲指定的frag)
return titles.get(position);
}
};
}
/**
* 初始化view
*/
private void initView() {
txt_show_toast = findViewById(R.id.txt_show_toast);
//viewpager
viewPager = findViewById(R.id.frag_two_viewpager);
//tablayout
frag_two_tabLayout = findViewById(R.id.frag_two_tabLayout);
//imageview
frag_two_img_add = findViewById(R.id.frag_two_img_add);
//設置點擊事件
frag_two_img_add.setOnClickListener(this);
/**
* 設置viewpager的滑動監聽事件(左右滑動)
*/
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// A.C_Log(getActivity(), "------->position=" + position);
}
@Override
public void onPageSelected(int position) {
Log.i("getActivity()", "onPageSelected----> + position=" + position);
DEFAULTFRAGMENT = position;
}
@Override
public void onPageScrollStateChanged(int state) {
// A.C_Log(getActivity(), "onPageScrollStateChanged");
}
});
}
/**
* 設置tablayout的指示器寬度
* @param tabs
* @param leftDip
* @param rightDip
*/
@Deprecated
public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
Class<?> tabLayout = tabs.getClass();
Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
tabStrip.setAccessible(true);
LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);
child.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
params.leftMargin = left;
params.rightMargin = right;
child.setLayoutParams(params);
child.invalidate();
}
}
/**
* 單擊事件
* @param v
*/
@Override
public void onClick(View v) {
int temdId = v.getId();
if(temdId == R.id.frag_two_img_add){
//跳轉進title管理界面
startActivity(new Intent(activity, AddTabItemActivity.class));
}
}
/**
* 將選中的值傳進來並顯示
* @param SELECTEDFRAGMENT
*/
public static void getSelectFrag(int SELECTEDFRAGMENT) {
//跳轉進viewpager指定的item
viewPager.setCurrentItem(SELECTEDFRAGMENT, false);
}
}
Frag_Two_Frag_Item.class
/**
* 第一個界面裏面所嵌套的公用frag
*/
public class Frag_Two_Frag_Item extends BaseFragment {
String item_title="默認";
public static String BUNDLE_TITLE = "title";
public static final String APPKEY = "0bea107901b817f31bafbda687d2753d";
public static FragTwoItemAdapter adapter;
List<News> datas = new ArrayList<>();
RecyclerView frag_item_listView;
ImageView img_itemtwofrag_load;
//獲取最後一個可見view的座標
int lastItemPosition;
//獲取第一個可見view的座標
int firstItemPosition;
/**
* handler
* 通過線程獲取數據並加載adapter
*/
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.arg1 == 10012){
Toast.makeText(getActivity(), R.string.getDataError, Toast.LENGTH_SHORT).show();
return;
}
img_itemtwofrag_load.clearAnimation();
img_itemtwofrag_load.setVisibility(View.GONE);
//設置RecyclerView的數據加載
frag_item_listView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new FragTwoItemAdapter(getActivity(), datas);
frag_item_listView.setAdapter(adapter);
adapter.setLinster(new FragTwoItemAdapter.ItemOnClickLinster(){
@Override
public void textItemOnClick(View view, int position) {
Log.i("getActivity()", "點擊事件");
Intent intent = new Intent(getActivity(), NewDetailActivity.class);
intent.putExtra("url", datas.get(position).getDateilurl());
intent.putExtra("img", datas.get(position).getThumbnail_pic_s());
intent.putExtra("title", datas.get(position).getTitle());
startActivity(intent);
}
});
}
};
Map<String, String> params;
@Override
protected int setContentView() {
return R.layout.frag_two_frag_item;
}
@Override
protected void init() {
Bundle bundle = getArguments();
if(bundle != null){
item_title = bundle.getString(BUNDLE_TITLE);
}
frag_item_listView = rootView.findViewById(R.id.frag_item_listView);
img_itemtwofrag_load = rootView.findViewById(R.id.img_itemtwofrag_load);
}
@Override
protected void lazyLoad() {
img_itemtwofrag_load.setVisibility(View.VISIBLE);
openA(getActivity(), img_itemtwofrag_load);
handler.post(getDatas);
frag_item_listView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState == RecyclerView.SCROLL_STATE_IDLE ){
Log.i("getActivity()", "這裏應該是一動不動的");
//這裏滑動停止,開始加載可見項
System.out.println(firstItemPosition + " " + lastItemPosition);
adapter.setScrolling(false);
adapter.notifyDataSetChanged();
}else if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
Log.i("getActivity()", "這裏應該是開始滑動");
//這裏做處理(停止加載一切事情)
adapter.setScrolling(true);
}else if(newState == RecyclerView.SCROLL_STATE_SETTLING){
Log.i("getActivity()", "這裏應該是手指離開屏幕的事件");
//
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//判斷是當前layoutManager是否爲LinearLayoutManager
// 只有LinearLayoutManager纔有查找第一個和最後一個可見view位置的方法
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
//獲取最後一個可見view的位置
lastItemPosition = linearManager.findLastVisibleItemPosition();
//獲取第一個可見view的位置
firstItemPosition = linearManager.findFirstVisibleItemPosition();
}
}
});
//如果確定每個item的內容不會改變RecyclerView的大小,設置這個選項可以提高性能
frag_item_listView.setHasFixedSize(true);
frag_item_listView.setItemAnimator(new DefaultItemAnimator());
}
/**
* 獲取數據
*/
Runnable getDatas = new Runnable() {
@Override
public void run() {
switch (item_title){
case "頭條":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.toutiao, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "社會":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.shehui, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "國內":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.guonei, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "國際":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.guoji, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "娛樂":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.yule, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "體育":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.tiyu, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "軍事":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.junshi, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "科技":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.keji, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "財經":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.caijing, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
case "時尚":
params = new HashMap<>();
params.put("key", APPKEY);
HttpRequest.post(HTTPURLS.shishang, (HashMap<String, String>) params, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponse = response.body().string();
Log.i("getActivity()", "===" + reponse);
JsonDta(reponse);
}
});
break;
default :
break;
}
}
};
/**
* 解析json數據
* @param reponse
*/
private void JsonDta(String reponse) {
//創建對象接收返回的數據
TwoFragData data = null;
data = new Gson().fromJson(reponse, TwoFragData.class);
if(data.getError_code() != 0){
//模仿網絡請求返回的參數
Message message = handler.obtainMessage();
message.arg1 = data.getError_code();
handler.sendMessage(message);
}else {
for (int i = 0; i < data.getResult().getData().size(); i++){
News newInfo = new News();
newInfo.setUniquekey(data.getResult().getData().get(i).getUniquekey());
newInfo.setTitle(data.getResult().getData().get(i).getTitle());
newInfo.setDate(data.getResult().getData().get(i).getDate());
newInfo.setCategory(data.getResult().getData().get(i).getCategory());
newInfo.setAuthor_name(data.getResult().getData().get(i).getAuthor_name());
newInfo.setDateilurl(data.getResult().getData().get(i).getUrl());
newInfo.setThumbnail_pic_s(data.getResult().getData().get(i).getThumbnail_pic_s());
newInfo.setThumbnail_pic_s02(data.getResult().getData().get(i).getThumbnail_pic_s02());
newInfo.setThumbnail_pic_s03(data.getResult().getData().get(i).getThumbnail_pic_s03());
datas.add(newInfo);
}
//模仿網絡請求返回的參數
Message message = handler.obtainMessage();
handler.sendMessage(message);
}
}
/**
* 傳值
* @param item_title
* @return
*/
public static Frag_Two_Frag_Item getInstance(String item_title){
Bundle bundle = new Bundle();
bundle.putString(BUNDLE_TITLE, item_title);
Frag_Two_Frag_Item frag_two_frag_item = new Frag_Two_Frag_Item();
frag_two_frag_item.setArguments(bundle);
return frag_two_frag_item;
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
StatusBarCompat.setStatusBarColor(getActivity(), ContextCompat.getColor(getContext(), R.color.cyan));
}
}
/**
* 開啓一個動畫
* @param img
*/
public static void openA(Activity activity, ImageView img){
//加載loading動畫
rotateAnimation = AnimationUtils.loadAnimation(activity, R.anim.loading);
LinearInterpolator interpolator = new LinearInterpolator();
rotateAnimation.setInterpolator(interpolator);
img.startAnimation(rotateAnimation);
}
private static Animation rotateAnimation;
}
FragTwoItemAdapter.class
public class FragTwoItemAdapter extends RecyclerView.Adapter<FragTwoItemAdapter.ViewHolder> {
Activity context;
List<News> data;
LayoutInflater inflater;
View view;
/**
* 圖片緩存技術的核心類,用於緩存所有下載好的圖片,在程序內存達到設定值時會將最少最近使用的圖片移除掉。
*/
LruCache<String, BitmapDrawable> mMemoryCache;
public FragTwoItemAdapter(Activity activity, List<News> datas){
this.context = activity;
this.data = datas;
inflater = LayoutInflater.from(activity);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.frag_two_frag_listview_item, parent, false);
return new ViewHolder(view);
}
/** 標記是否正在滑動,如果爲true,就暫停加載圖片 */
protected boolean isScrolling = false;
/**
* 賦值
* @param scrolling
*/
public void setScrolling(boolean scrolling) {
isScrolling = scrolling;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onBindViewHolder(final ViewHolder viewHolder, int position) {
//改變item的背景
ChangeItemBG(viewHolder);
viewHolder.txt_title.setText(data.get(position).getTitle());
viewHolder.txt_content.setText(data.get(position).getAuthor_name());
viewHolder.txt_time.setText(data.get(position).getDate());
//圖片加載框架
Glide
.with(context)
.load(data.get(position).getThumbnail_pic_s())
.placeholder(R.mipmap.default_image)
.error(R.mipmap.default_image)
.into(viewHolder.img_icon);
}
/**
* 改變背景
* @param viewHolder
*/
private void ChangeItemBG(ViewHolder viewHolder) {
viewHolder.txt_title.setBackgroundResource(R.color.transparent);
viewHolder.txt_content.setBackgroundResource(R.color.transparent);
viewHolder.txt_time.setBackgroundResource(R.color.transparent);
RelativeLayout.LayoutParams txt_title = (RelativeLayout.LayoutParams) viewHolder.txt_title.getLayoutParams();
txt_title.width = LinearLayout.LayoutParams.WRAP_CONTENT;
txt_title.height = LinearLayout.LayoutParams.WRAP_CONTENT;
viewHolder.txt_title.setLayoutParams(txt_title);
LinearLayout.LayoutParams txt_content = (LinearLayout.LayoutParams) viewHolder.txt_content.getLayoutParams();
txt_content.width = LinearLayout.LayoutParams.WRAP_CONTENT;
txt_content.height = LinearLayout.LayoutParams.WRAP_CONTENT;
viewHolder.txt_content.setLayoutParams(txt_content);
LinearLayout.LayoutParams txt_time = (LinearLayout.LayoutParams) viewHolder.txt_time.getLayoutParams();
txt_time.width = LinearLayout.LayoutParams.WRAP_CONTENT;
txt_time.height = LinearLayout.LayoutParams.WRAP_CONTENT;
viewHolder.txt_time.setLayoutParams(txt_time);
}
@Override
public int getItemCount() {
return data.size();
}
/**
* //自定義的ViewHolder,持有每個Item的的所有界面元素
*/
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txt_title, txt_content, txt_time;
public ImageView img_icon;
public LinearLayout lin_all;
public ViewHolder(View rootView) {
super(rootView);
this.lin_all = rootView.findViewById(R.id.lin_all);
this.img_icon = rootView.findViewById(R.id.img_icon);
this.txt_title = rootView.findViewById(R.id.txt_title);
this.txt_content = rootView.findViewById(R.id.txt_content);
this.txt_time = rootView.findViewById(R.id.txt_time);
lin_all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Linster.textItemOnClick(v, getPosition());
}
});
}
}
public ItemOnClickLinster Linster;
public void setLinster(ItemOnClickLinster linster) {
Linster = linster;
}
public interface ItemOnClickLinster{
void textItemOnClick(View view, int position);
}
}
frag_two_frag_listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/dimen_10_dip">
<LinearLayout
android:id="@+id/lin_all"
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_110_dip"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="@+id/img_icon"
android:layout_width="@dimen/dimen_85_dip"
android:layout_height="@dimen/dimen_85_dip"
android:layout_gravity="center"
android:baselineAligned="false"
android:contentDescription="TODO"
android:scaleType="fitXY"
android:src="@mipmap/default_image" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_85_dip"
android:layout_marginLeft="@dimen/dimen_10_dip"
android:orientation="vertical"
android:layout_gravity="center">
<TextView
android:id="@+id/txt_title"
android:layout_width="@dimen/dimen_100_dip"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="@color/gainsboro"
android:textColor="@color/black"
android:textSize="@dimen/dimen_18_dip" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:orientation="horizontal">
<TextView
android:id="@+id/txt_content"
android:layout_width="@dimen/dimen_120_dip"
android:layout_height="wrap_content"
android:background="@color/gainsboro"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/dimen_14_dip" />
<TextView
android:id="@+id/txt_time"
android:layout_width="@dimen/dimen_150_dip"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dimen_15_dip"
android:background="@color/gainsboro"
android:gravity="center"
android:textColor="@color/black"
android:textSize="@dimen/dimen_14_dip" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="@dimen/dimen_0.5_dip"
android:background="@color/gainsboro" />
</LinearLayout>
其實吧,整個功能沒有難懂的地方,只要理解了代碼,換到自己的項目裏面能夠熟練的使用就可以,可以根據不同的需求去定製不同的實現方式,而這裏的這種方式只是一種,給大家借鑑一下而已,同時有什麼好方法也可以給我推薦下,代碼的不足也可以指出!!
附上demo源碼,因不太熟練GitHub,所以這裏的鏈接還是csdn的。
點這裏下載源碼,快,戳我戳我…
本文引用GitHub的刷新框架,不擁有解釋權,如果想進一步瞭解刷新框架,請前往下面的地址閱讀
https://github.com/scwang90/SmartRefreshLayout
q:486789970
email:[email protected]
如果有什麼問題,歡迎大家指導。並相互聯繫,希望能夠通過文章互相學習。
---財財親筆