大家好,又见面了,我是你们的朋友全栈君。
代码很简单,记录一下
主要是用LinkedList在destroyItem中添加移除的View,在instantiateItem中复用移除的View。
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private PagerAdapter mPagerAdapter;
private List<String> mDataList = new ArrayList<>();
private Button mUpdate, mDelete, mAdd, mClean;
private LinkedList<View> mViewCache = new LinkedList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataList.add("1");
mDataList.add("2");
mDataList.add("3");
mDataList.add("4");
mDataList.add("5");
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(mPagerAdapter = new PagerAdapter() {
@Override
public int getCount() {
return mDataList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = mViewCache.size() > 0 ? mViewCache.removeFirst() : null;
String str = "";
if (view == null) {
view = View.inflate(MainActivity.this, R.layout.item_pager, null);
str = "";
} else{
str = "复用了position为= " + view.getTag() + " 的Item";
}
TextView textView = view.findViewById(R.id.pager_tv);
textView.setText(str + "\n" +mDataList.get(position));
view.setTag(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View deleteView = (View) object;
container.removeView(deleteView);
mViewCache.add(deleteView);
}
});
}
}
微信公众号
随意打赏
QQ群:365473065
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/163220.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...