首先來建立一個很常見的Viewpager+Fragment的佈局。android
package com.dubhe.view.fragment
import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.dubhe.view.R
import com.dubhe.view.config.Constant
import com.dubhe.view.mvp.model.ServiceModel
import kotlinx.android.synthetic.main.item.*
class MyFragment : Fragment() {
companion object {
//data是傳入的數據Model對象
fun newInstance(data: MyDataModel): MyFragment {
val args = Bundle()
args.putSerializable("data", data)
val fragment = MyFragment()
fragment.arguments = args
return fragment
}
}
/** * 刷新數據 */
fun setData(data: MyDataModel) {
initView(rootView, data)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// initView(view, imgID)
// rootView = inflater.inflate(R.layout.item_wash_service2, container, false)
rootView = View.inflate(activity, R.layout.item_wash_service2, null)
return rootView
}
var hindPrice = false
lateinit var rootView: View
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val data = arguments!!.getSerializable("data") as MyDataModel
initView(view, data)
}
@SuppressLint("SetTextI18n")
private fun initView(view: View, data: MyDataModel) {
//TODO:在此處將Model裏的數據加載到界面
//Java要用view.findViewById來取控件
//Kotlin直接用ID調用就好
}
複製代碼
private var listDatas: MutableList<MyDataModel> = ArrayList()
listDatas.clear()
listDatas.addAll(model.list)
for (item in listDatas) {
val position = listDatas.indexOf(item)
if (position < list.size) {
//已經存在的項,刷新數據
val fragment = list[position] as CarWashPageFragment2
fragment.setData(listDatas[position])
} else {
//添加不存在的項
val fragment = CarWashPageFragment2.newInstance(item)
list.add(fragment)
}
}
if (viewPager.adapter == null) {
viewPager.adapter = object : MyPagerAdapter(supportFragmentManager, list) {
override fun getItem(i: Int): Fragment {
return list[i]
}
override fun getCount(): Int {
return list.size
}
}
}
viewPager.offscreenPageLimit = list.size//緩存
viewPager.adapter?.notifyDataSetChanged()
複製代碼
public abstract class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> pages;
public MyPagerAdapter(FragmentManager fragmentManager, List<Fragment> pages) {
super(fragmentManager);
this.pages = pages;
}
@Override
public Fragment getItem(int index) {
return pages.get(index);
}
@Override
public int getCount() {
return pages.size();
}
@Override
public int getItemPosition(Object object) {
int index = pages.indexOf (object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
}
複製代碼
往後再更_(:з」∠)_緩存