android 如何修复”3片段在一个活动与viewPager需要验证前两页,然后可能去第三页”

dced5bon  于 2023-03-16  发布在  Android
关注(0)|答案(2)|浏览(94)

我想创建一个createOrderActivity,其中包含三个片段,如服务信息、调度信息和确认
服务信息片段具有editText,如果单击Next按钮(位于CreateOrderActivity),则首先检查验证editText。然后移动ScheduleFragment页面。如果前两个页面验证通过,则移动到ConfirmationFragment页面。
下面是FragmentViewpagerAdapter类

public class FragmentViewPagerAdapter extends FragmentPagerAdapter {

private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();

public FragmentViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return fragmentList.get(position);
}

@Override
public int getCount() {
    return fragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    fragmentList.add(fragment);
    fragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
    return fragmentTitleList.get(position);
}

}
在创建订单活动类中

@Override
        public void onPageSelected(int position) {

            boolean checkSch= false;
            if (position == 1) {

                ServiceInfoFragment serviceInfoFragment = new ServiceInfoFragment();

                //checking validation from ServiceInfoFragment fragment Class
                if (serviceInfoFragment.checkServiceValidation()) {

                    checkSch = true;
                    //Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
                }else {
                    checkSch = false;
                   // Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
                    pagerCreateOrder.setCurrentItem(position-1);
                }
            }
            if (position == 2) {

                if (checkSch){
                    ScheduleFragment scheduleFragment = new ScheduleFragment();
                    if (scheduleFragment.checkScheduleValidation()) {
                        Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(CreateOrderActivity.this, "Please check S validation", Toast.LENGTH_SHORT).show();
                        pagerCreateOrder.setCurrentItem(position-1);
                    }

                }else {

                    Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
                    pagerCreateOrder.setCurrentItem(position-2);
                }

            }

        }

//检查ScheduleFragment类中的checkScheduleValidation(),返回空异常

  • 在片段中声明的波纹管方法 *
public boolean checkServiceValidation(){

    return true;
}

我上传此图片

I used this Reference

2hh7jdfx

2hh7jdfx1#

我用自己的方式找到了一个解决方案。我已经在一个视图页中加载了三个片段。在第二个片段中,有一个edittext。在单击下一个按钮时,有一个检查电子邮件的验证。在验证的基础上加载下一个片段。所有片段都作为单个片段加载。由于片段的多个示例,您可能会导致空指针异常。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private FragmentTwo fragmentTwo;

private ViewPager mViewPager;
Button back, next;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    back = findViewById(R.id.back);
    next = findViewById(R.id.next);
    next.setOnClickListener(this);
    back.setOnClickListener(this);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.vp_viewpager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            if (i==2){
                if (!fragmentTwo.checkEditText()) {
                    Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_LONG).show();
                    mViewPager.setCurrentItem(i-1);
                    return;
                }
            }

        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

}

private void changeViewPagerPosition(int position) {
    int totalCount = mViewPager.getAdapter().getCount();
    if (position < 0 || position >= totalCount) {
        return;
    }
    mViewPager.setCurrentItem(position);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public void onClick(View view) {
    int currentViewpagerPosition = mViewPager.getCurrentItem();

    switch (view.getId()) {
        case R.id.back:
            changeViewPagerPosition(currentViewpagerPosition - 1);
            break;
        case R.id.next:
            if (currentViewpagerPosition==1){
                if (!fragmentTwo.checkEditText()) {
                    Toast.makeText(getApplicationContext(),"Falsee",Toast.LENGTH_LONG).show();
                    return;
                }

            }
            changeViewPagerPosition(currentViewpagerPosition + 1);
            break;
    }
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {

            case 0:
                return FragmentOne.newInstance(position);
            case 1:
                return fragmentTwo=FragmentTwo.getInstance();
            case 2:
                return FragmentThree.newInstance(position);
            default:
                return FragmentThree.newInstance(position);

        }

    }

    @Override
    public int getCount() {
        return 3;
    }
}

}
碎片2

public  class FragmentTwo extends Fragment  {

EditText email;
private static FragmentTwo fragment=null;

public FragmentTwo() {
}

public static FragmentTwo getInstance() {
    if (fragment == null){
        fragment = new FragmentTwo();
    }
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_two, container, false);
   return rootView;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    email = getView().findViewById(R.id.editText);

}

public boolean emailValidator()
{
    Pattern pattern;
    Matcher matcher;
    final String EMAIL_PATTERN = "^[_A-Za-z0-" +
            "9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email.getText().toString());
    return matcher.matches();
}

public Boolean checkEditText(){
    if (emailValidator()){
        return true;
    }
    return false;
}

}

mf98qq94

mf98qq942#

Kotlin:使用此代码=在一个活动中附加框架视图容器,然后包括所有片段*工作正常 *
XML活动

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/rl_toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dim_60_dp">

        <ImageView
            android:id="@+id/img_survey_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_back"
            app:tint="@color/white"
            android:layout_marginStart="@dimen/dim_5_dp"
            android:padding="@dimen/dim_8_dp"/>

        <TextView
            android:id="@+id/txt_house_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/img_survey_back"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:fontFamily="@font/font_medium"
            android:textColor="@color/white"
            android:textSize="18sp"
            android:text="@string/title_survey_info"/>
        <TextView
            android:id="@+id/txt_house_id_num"
            android:layout_below="@+id/txt_house_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/img_survey_back"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:fontFamily="@font/font_medium"
            android:textColor="@color/white"
            android:textSize="@dimen/dim_14_sp"
            android:text="House Id"/>

    </RelativeLayout>
    <TextView
        android:id="@+id/txt_no_connection"
        android:layout_below="@id/rl_toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dim_30_dp"
        android:background="@color/black_alpha_5"
        android:textColor="@color/yellow"
        android:gravity="center"
        android:textSize="16sp"
        android:layout_centerHorizontal="true"
        android:visibility="visible"
        android:layout_marginVertical="@dimen/dim_10_dp"
        android:fontFamily="@font/font_bold"
        android:text="@string/no_internet_error"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_marginHorizontal="@dimen/dim_10_dp"
        android:layout_below="@id/txt_no_connection">

        <RelativeLayout
            android:id="@+id/viewPagerIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginVertical="@dimen/dim_10_dp"
            android:orientation="horizontal">

            <com.tbuonomo.viewpagerdotsindicator.DotsIndicator
                android:id="@+id/dots_indicator"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:dotsColor="@color/colorSurveyEditGreenLight"
                app:dotsCornerRadius="8dp"
                app:dotsSize="16dp"
                app:dotsSpacing="4dp"
                app:dotsWidthFactor="2.5"
                app:selectedDotColor="@color/white"
                app:progressMode="true"
                />

        </RelativeLayout>

        <FrameLayout
            android:id="@+id/container_frame_layout"
            android:layout_below="@id/viewPagerIndicator"
            android:layout_above="@id/rl_btn_box"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.viewpager2.widget.ViewPager2
                android:id="@+id/view_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layoutDirection="ltr"/>

            <ProgressBar
                android:id="@+id/progress_bar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="?android:attr/progressBarStyleLarge"
                android:indeterminate="true"
                android:indeterminateTintMode="src_atop"
                android:indeterminateTint="@color/colorSurveyWhite"
                android:layout_gravity="center"
                android:visibility="gone"/>

        </FrameLayout>

        <RelativeLayout
            android:id="@+id/rl_btn_box"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginHorizontal="@dimen/dim_10_dp">

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/btn_next"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_gravity="center"
                android:layout_marginVertical="@dimen/dim_20_dp"
                android:layout_marginEnd="@dimen/dim_10_dp"
                android:background="@drawable/round_button"
                android:elevation="@dimen/dim_10_dp"
                android:fontFamily="@font/font_bold"
                android:textAllCaps="false"
                android:padding="@dimen/dim_10_dp"
                android:shadowColor="@color/colorGray"
                android:text="@string/btn_next"
                android:visibility="gone"
                android:textColor="@color/colorSurveyTextBlue" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/btn_done"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_gravity="center"
                android:layout_marginVertical="@dimen/dim_20_dp"
                android:layout_marginEnd="@dimen/dim_10_dp"
                android:background="@drawable/round_button"
                android:elevation="@dimen/dim_10_dp"
                android:fontFamily="@font/font_bold"
                android:textAllCaps="false"
                android:padding="@dimen/dim_10_dp"
                android:visibility="gone"
                android:shadowColor="@color/colorGray"
                android:text="@string/btn_done"
                android:textColor="@color/colorSurveyTextBlue"/>
            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/btn_update"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_gravity="center"
                android:layout_marginVertical="@dimen/dim_20_dp"
                android:layout_marginEnd="@dimen/dim_10_dp"
                android:background="@drawable/round_button"
                android:elevation="@dimen/dim_10_dp"
                android:fontFamily="@font/font_bold"
                android:textAllCaps="false"
                android:padding="@dimen/dim_10_dp"
                android:shadowColor="@color/colorGray"
                android:text="Update"
                android:visibility="gone"
                android:textColor="@color/colorSurveyTextBlue"/>
            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/btn_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/round_button"
                android:text="@string/btn_back"
                android:fontFamily="@font/font_bold"
                android:layout_alignParentStart="true"
                android:layout_centerVertical="true"
                android:textAllCaps="false"
                android:layout_marginVertical="@dimen/dim_20_dp"
                android:layout_marginStart="@dimen/dim_10_dp"
                android:textColor="@color/colorSurveyTextBlue"
                android:padding="@dimen/dim_10_dp"
                android:elevation="@dimen/dim_10_dp"
                android:shadowColor="@color/colorGray"
                android:layout_gravity="center"
                android:visibility="gone"/>

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

Kotlin文件-仅方法

private fun setUpViewPager(){

    val fragmentList : MutableList< Fragment> = mutableListOf()
    fragmentList.add(SurveyPageOneFragment.newInstance(true))
    fragmentList.add(SurveyPageTwoFragment.newInstance(true))
    fragmentList.add(SurveyPageThreeFragment.newInstance(true))
    fragmentList.add(SurveyPageFourFragment.newInstance(true))
    fragmentList.add(SurveyPageFiveFragment.newInstance(true))

    surveyPagerAdapter = SurveyPagerAdapter(fragmentList,supportFragmentManager,lifecycle)
    binding.viewPager.adapter = surveyPagerAdapter
    binding.dotsIndicator.attachTo(binding.viewPager)

}

设置单击时方法

private fun setOnClick(){
    binding.btnNext.setOnClickListener {
        if (binding.viewPager.currentItem < binding.viewPager.adapter?.itemCount!!){
            when (fragPosition) {
                0 -> {
                    Log.i("TAG", "Page 1: Position $fragPosition")
                    binding.viewPager.currentItem = binding.viewPager.currentItem +1
                }
                1 -> {
                    Log.i("TAG", "Page 2: Position $fragPosition")
                    binding.viewPager.currentItem = binding.viewPager.currentItem +1
                }
                2 -> {
                    Log.i("TAG", "Page 3: Position $fragPosition")
                    binding.viewPager.currentItem = binding.viewPager.currentItem +1
                }
                3 -> {
                    Log.i("TAG", "Page 4: Position $fragPosition")
                    binding.viewPager.currentItem = binding.viewPager.currentItem +1
                }
                4 -> {
                    Log.i("TAG", "Page 5: Position $fragPosition")
                    binding.viewPager.isUserInputEnabled = true
                    binding.viewPager.currentItem = binding.viewPager.currentItem +1
                }
            }
        }
    }

    binding.btnBack.setOnClickListener {
        if (binding.viewPager.currentItem != 0){
            binding.viewPager.currentItem = binding.viewPager.currentItem -1
        }
    }

    binding.btnDone.setOnClickListener {
        startActivity(Intent(context,SurveyCompleteActivity::class.java))
    }

    val onPageChangeCallback = object : OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            Log.i("TAG", "PageChange: $position")
            fragPosition = position

            if (position == 0){
                binding.btnBack.visibility = View.GONE
            }else{
                binding.btnBack.visibility = View.VISIBLE
            }

            if (position < binding.viewPager.adapter?.itemCount!! -1){
                binding.btnNext.visibility = View.VISIBLE
                binding.btnDone.visibility = View.GONE
            }else{
                binding.btnNext.visibility = View.GONE
                binding.btnDone.visibility = View.VISIBLE
                binding.viewPager.isUserInputEnabled = false
            }

        }
    }
    binding.viewPager.registerOnPageChangeCallback(onPageChangeCallback)
}

查看寻呼机适配器

class SurveyPagerAdapter(
private val fragmentList: MutableList< Fragment>,
fragment: FragmentManager,
lifecycle: Lifecycle) : FragmentStateAdapter(fragment,lifecycle){
override fun getItemCount(): Int = fragmentList.size

override fun createFragment(position: Int): Fragment {
    return fragmentList[position]
}

fun getFragmentName(position: Int) = fragmentList[position]

fun addFragment(fragment: Fragment) {
    fragmentList.add(fragment)
    notifyDataSetChanged()
}}

使用了相似片段

class SurveyPageFiveFragment : Fragment() {
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentSurveyPageFiveBinding.inflate(inflater, container, false)
    return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    init()
}
override fun onDestroy() {
    super.onDestroy()
    _binding = null
}
companion object {
    @JvmStatic
    fun newInstance(isMyBoolean: Boolean) = SurveyPageFiveFragment().apply {
        val fragment = SurveyPageFiveFragment()
        arguments = Bundle().apply {
            putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
        }
        fragment.arguments
        return fragment
    }
}}

相关问题