一、简介:
1、添加和删除按钮可动态添加删减tab页面
2、获取每个fragment数据页上的数据
3、为每个数据页赋值
二、 效果图:
三、实现:
主要功能实现:(ViewPage2Fragment.java)
先初始化适配器
// 加载自定义的布局文件
view = inflater.inflate(R.layout.activity_viewpage2_plan_filling_upload, null);
tabLayoutUp = view.findViewById(R.id.tab_layout);
viewPagerUp = view.findViewById(R.id.view_pager);
delImage = view.findViewById(R.id.delete);
addImage = view.findViewById(R.id.add);
lastPlan = view.findViewById(R.id.lastPlan);
tvProName = view.findViewById(R.id.tv_pro_name);
tvTime = view.findViewById(R.id.tv_time);
Button upload = view.findViewById(R.id.upload);
tabLayoutUp.setTabMode(MODE_SCROLLABLE);//适合很多tab
//tabLayoutUp.setTabMode(MODE_FIXED);//tab均分,适合少的tab
tabLayoutUp.addOnTabSelectedListener(this);
viewPagerUp.setAdapter(mAdapter);
// 设置缓存的数量
viewPagerUp.setOffscreenPageLimit(1);
new TabLayoutMediator(tabLayoutUp, viewPagerUp, (tab, position) -> tab.setText(mAdapter.getPageTitle(position))).attach();
//初始化生成第一个页面
refreshAdapter(true);
//此处只删除最后一个页面
delImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = mAdapter.getItemCount();
mAdapter.removeFragment(count - 1);
mAdapter.notifyDataSetChanged();
}
});
//添加页面
addImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = mAdapter.getItemCount();
mAdapter.addFragment(count, ViewPage2DataFragment.newInstance(count + ""), (count + 1) + "");
mAdapter.notifyDataSetChanged();
}
});
//计划名称
tvProName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSimpleBottomSheetList();
}
});
//时间选择
tvTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDatePicker();
}
});
//导入上次计划
lastPlan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLastPlan();
}
});
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<PlanBean> listBean = new ArrayList<>();
//获取fragment数据页的数量
int count = mAdapter.getItemCount();
if (count > 0) {
if (StringHelper.isEmptyAndNull(tvProName.getText().toString())) {
XToastUtils.error("计划名称为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(tvTime.getText().toString())) {
XToastUtils.error("时间为空,请填写!");
return;
}
for (int i = 0; i < count; i++) {
//遍历获取每个fragment数据页
ViewPage2DataFragment st = (ViewPage2DataFragment) mAdapter.createFragment(i);
//调用数据页的方法得到数据放在listBean中 getData方法在ViewPage2DataFragment中
listBean.add(st.getData());
}
for (int j = 0; j < listBean.size(); j++) {
listBean.get(j).setProName(proNameId);
listBean.get(j).setMonth(tvTime.getText().toString());
if (StringHelper.isEmptyAndNull(listBean.get(j).getZynr())) {
XToastUtils.error("第" + (j + 1) + "页数据一内容为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(listBean.get(j).getFxdj())) {
XToastUtils.error("第" + (j + 1) + "页数据二内容为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(listBean.get(j).getTdsj())) {
XToastUtils.error("第" + (j + 1) + "页数据三内容为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(listBean.get(j).getTdsb())) {
XToastUtils.error("第" + (j + 1) + "页数据四内容为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(listBean.get(j).getSsgdj())) {
XToastUtils.error("第" + (j + 1) + "页数据五内容为空,请填写!");
return;
} else if (StringHelper.isEmptyAndNull(listBean.get(j).getFzr())) {
XToastUtils.error("第" + (j + 1) + "页数据六内容为空,请填写!");
return;
}
}
//提交方法 listBean里为页面上的数据
upData(listBean);
} else {
XToastUtils.error("未获取到数据,请添加数据后再提交!");
}
}
});
/**
* 导入上次计划
* 接口数据已注释,此处为固定假数据,实际环境根据接口返回数据显示
*/
private void getLastPlan() {
// String url ="接口url";
// FormBody body = new FormBody.Builder()
// .build();
// String result = service.httpPost(url,body);
// if(!StringHelper.isEmptyAndNull(result)){
// try {
// org.json.JSONObject jsonObject = new org.json.JSONObject(result);
// String res = jsonObject.getString("res");
// if("0".equals(res)){
// XToastUtils.error("获取失败!");
// }else{
// JSONArray jsonArray = jsonObject.getJSONArray("obj");
//将当前页面上的fragment数据页全部删除
mAdapter.removeFragmentAll();
//刷新
mAdapter.notifyDataSetChanged();
ViewPage2DataFragment viewPage2DataFragment=new ViewPage2DataFragment();
for (int i = 0; i < 2; i++) {
PlanBean bean = new PlanBean();
// JSONObject js = jsonArray.getJSONObject(i);
// bean.setZynr(js.getString("zynr"));
bean.setZynr("数据一一一");
bean.setFxdj("数据二二二");
bean.setTdsj("数据三三三");
bean.setTdsb("数据四四四");
bean.setSsgdj("数据五五五");
bean.setFzr("数据六六六");
bean.setBz("备注备注");
//添加页面 bean则为要显示到页面上的数据
mAdapter.addFragment(i, viewPage2DataFragment.newInstances((i+1)+"",bean), (i+1)+"");
//刷新
mAdapter.notifyDataSetChanged();
//制定初始化的页面 0则为制定第一个页面为当前页面
viewPager.setCurrentItem(0, false);
}
// }
// } catch (JSONException e) {
// XToastUtils.error("解析异常,请重试!");
// }
// }
}
/**
* 计划名称列表
*/
private void showSimpleBottomSheetList() {
new BottomSheet.BottomListSheetBuilder(getActivity())
.setTitle("计划名称")
.addItem("aaaa")
.addItem("bbbb")
.addItem("cccc")
.addItem("dddd")
.setIsCenter(true)
.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
dialog.dismiss();
tvProName.setText(tag);
})
.build()
.show();
}
/**
* 时间选择器
*/
private void showDatePicker() {
if (mDatePicker == null) {
mDatePicker = new TimePickerBuilder(getContext(), (date, v) -> tvTime.setText(DateUtils.date2String(date, DateUtils.yyyyMMdd.get())))
.setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
.setTitleText("日期选择")
.build();
}
mDatePicker.show();
}
/**
* 保存提交数据
*/
private void upData(List<PlanBean> listBean) {
//提交数据
}
/**
* 生成第一个页面
*/
private void refreshAdapter(boolean isShow) {
if (viewPagerUp == null) {
return;
}
if (isShow) {
// 动态加载选项卡内容
mAdapter.addFragment(ViewPage2DataFragment.newInstance("1"), "1");
mAdapter.notifyDataSetChanged();
viewPagerUp.setCurrentItem(0, false);
WidgetUtils.setTabLayoutTextFont(tabLayoutUp);
} else {
mAdapter.clear();
}
}
frament数据页(ViewPage2DataFragment.java)
public class ViewPage2DataFragment extends Fragment {
private static final String KEY_TITLE = "title";
public ViewPage2DataFragment viewPage2DataFragment;
@BindView(R.id.zynr)
EditText zynr;
@BindView(R.id.fxdj)
TextView fxdj;
@BindView(R.id.tdsj)
EditText tdsj;
@BindView(R.id.tdsb)
EditText tdsb;
@BindView(R.id.ssgdj)
EditText ssgdj;
@BindView(R.id.fzr)
EditText fzr;
@BindView(R.id.bz)
EditText bz;
private Unbinder mUnbinder;
@AutoWired(name = KEY_TITLE)
String title;
public static ViewPage2DataFragment instance;
public ViewPage2DataFragment() {
}
public static ViewPage2DataFragment newInstance(String title) {
Bundle args = new Bundle();
args.putString(KEY_TITLE, title);
ViewPage2DataFragment fragment = new ViewPage2DataFragment();
fragment.setArguments(args);
return fragment;
}
/**
* bean为生成页面时传来的数据,先存在Budle中,在下面的方法中取
*/
public ViewPage2DataFragment newInstances(String title, PlanBean bean) {
Bundle args = new Bundle();
args.putString(KEY_TITLE, title);
args.putString("zynr", bean.getZynr());
args.putString("fxdj", bean.getFxdj());
args.putString("tdsj", bean.getTdsj());
args.putString("tdsb", bean.getTdsb());
args.putString("ssgdj", bean.getSsgdj());
args.putString("fzr", bean.getFzr());
args.putString("bz", bean.getBz());
ViewPage2DataFragment fragment = new ViewPage2DataFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
XRouter.getInstance().inject(this);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewpage2_plan_filling_tab_data, container, false);
mUnbinder = ButterKnife.bind(this, view);
instance = this;
initClick();
initData();
return view;
}
private void initClick() {
fxdj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new BottomSheet.BottomListSheetBuilder(getActivity())
.setTitle("计划名称")
.addItem("aaaa")
.addItem("bbbb")
.addItem("cccc")
.addItem("dddd")
.setIsCenter(true)
.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
dialog.dismiss();
fxdj.setText(tag);
})
.build()
.show();
}
});
}
/**
* 初始化数据,取Bundle中的数据显示到页面
*/
private void initData() {
Bundle bundle = getArguments();
String zynr1 = bundle.getString("zynr");
String fxdj1 = bundle.getString("fxdj");
String tdsj1 = bundle.getString("tdsj");
String tdsb1 = bundle.getString("tdsb");
String ssgdj1 = bundle.getString("ssgdj");
String fzr1 = bundle.getString("fzr");
String bz1 = bundle.getString("bz");
zynr.setText(zynr1);
fxdj.setText(fxdj1);
tdsj.setText(tdsj1);
tdsb.setText(tdsb1);
ssgdj.setText(ssgdj1);
fzr.setText(fzr1);
bz.setText(bz1);
}
/**
* 获取页面上的数据
*/
public PlanBean getData() {
PlanBean bean = new PlanBean();
String zynr1 = zynr.getText().toString();
String fxdj1 = fxdj.getText().toString();
String tdsj1 = tdsj.getText().toString();
String tdsb1 = tdsb.getText().toString();
String ssgdj1 = ssgdj.getText().toString();
String fzr1 = fzr.getText().toString();
String bz1 = bz.getText().toString();
bean.setZynr(zynr1);
bean.setFxdj(fxdj1);
bean.setTdsj(tdsj1);
bean.setTdsb(tdsb1);
bean.setSsgdj(ssgdj1);
bean.setFzr(fzr1);
bean.setBz(bz1);
return bean;
}
@Override
public void onDestroyView() {
if (mUnbinder != null) {
mUnbinder.unbind();
}
super.onDestroyView();
}
}
适配器(FragmentStateViewPager2Adapter.java)
public class FragmentStateViewPager2Adapter extends FragmentStateAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mTitleList = new ArrayList<>();
private List<Long> mIds = new ArrayList<>();
private AtomicLong mAtomicLong = new AtomicLong(0);
public FragmentStateViewPager2Adapter(@NonNull Fragment fragment) {
super(fragment);
}
@NonNull
@Override
public Fragment createFragment(int position) {
return mFragmentList.get(position);
}
public FragmentStateViewPager2Adapter addFragment(Fragment fragment, String title) {
if (fragment != null) {
mFragmentList.add(fragment);
mTitleList.add(title);
mIds.add(getAtomicGeneratedId());
}
return this;
}
/**
* 添加
*/
public FragmentStateViewPager2Adapter addFragment(int index, Fragment fragment, String title) {
if (fragment != null && index >= 0 && index <= mFragmentList.size()) {
mFragmentList.add(index, fragment);
mTitleList.add(index, title);
mIds.add(index, getAtomicGeneratedId());
}
return this;
}
/**
* 删除
*/
public FragmentStateViewPager2Adapter removeFragment(int index) {
if (index >= 0 && index < mFragmentList.size()) {
mFragmentList.remove(index);
mTitleList.remove(index);
mIds.remove(index);
}
return this;
}
/**
* 删除所有
*/
public FragmentStateViewPager2Adapter removeFragmentAll() {
mFragmentList.clear();
mTitleList.clear();
mIds.clear();
return this;
}
private long getAtomicGeneratedId() {
return mAtomicLong.incrementAndGet();
}
@Override
public int getItemCount() {
return mFragmentList.size();
}
public void clear() {
mFragmentList.clear();
mTitleList.clear();
mIds.clear();
notifyDataSetChanged();
}
public CharSequence getPageTitle(int position) {
return mTitleList.get(position);
}
@Override
public long getItemId(int position) {
return mIds.get(position);
}
@Override
public boolean containsItem(long itemId) {
return mIds.contains(itemId);
}
}
主布局(activity_viewpage2_plan_filling_upload.xml)
( 注:这里为了减少代码量,删除了计划名称、选择时间、导入计划、保存提交的布局)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efefef"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#F7F7F7"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="0.9" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.6"
android:orientation="vertical">
<ImageView
android:id="@+id/delete"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:src="@drawable/delete" />
</LinearLayout>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
style="@style/TabLayoutStyle"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="2" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.6"
android:orientation="vertical">
<ImageView
android:id="@+id/add"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:src="@drawable/add" />
</LinearLayout>
<View
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_weight="0.9" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
数据页布局(fragment_viewpage2_plan_filling_tab_data.xml)文章来源:https://www.toymoban.com/news/detail-599696.html
(注:这里为了减少代码量,删除了数据二、数据三等下面的布局,都是重复的布局,只是id不同)文章来源地址https://www.toymoban.com/news/detail-599696.html
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#efefef"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/write"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.1"
android:text="*"
android:textColor="@color/red"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2.5"
android:text="数据一"
android:textColor="#303133"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:orientation="horizontal">
<EditText
android:id="@+id/zynr"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_weight="1.1"
android:background="@drawable/bg_edittext"
android:gravity="center_vertical"
android:hint="请填写"
android:inputType="textMultiLine"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:layout_width="32dp"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>
到了这里,关于Android——viewpage2+tablayout+fragment动态添加删除的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!