如何通过 activity 中的按钮为 viewpager 中的不同片段提供侦听器

How to provide listeners for different fragment in a viewpager from a button in activity

我正在尝试使用 viewpager 中的片段创建一个表单,这是一个循序渐进的过程。

viewpager 中有 6 个片段。一个 "Back" 按钮和一个 "Next" 按钮(在 activity 中)。

我想在用户单击 "Next" 按钮时保存表单。

参考这里是代码

加载片段的适配器

public class RegistrationPagerAdapter extends FragmentPagerAdapter {

Fragment fragment;


public RegistrationPagerAdapter(@NonNull FragmentManager fm, int behavior) {
 super(fm, behavior);
}

@NonNull
@Override
public Fragment getItem(int position) {
 switch (position){
  case 0:
   fragment = new PersonalDetailsFragment();
  break;

  case 1:
   fragment = new AboutMeFragment();
  break;

  case 2:
   fragment = new HoroscopeFragment();
  break;

  case 3:
   fragment = new EducationFragment();
  break;

  case 4:
   fragment = new FamilyFragment();
  break;

  case 5:
   fragment = new ExpectationFragment();
   break;

 }
    return fragment;
}

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

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

}

activity中有两个按钮(不在片段中)

public class FormActivity extends AppCompatActivity implements View.OnClickListener {

private static final String TAG = "FormActivity";

AppCompatButton backButton, nextButton;
CustomViewPager viewpager;
Toolbar toolbar;
ApiInterface apiInterface;
RegistrationPagerAdapter adapter;
int status;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form);
    initilizeToolbar();

}

@Override
protected void onRestart() {
    super.onRestart();
}

private void initilizeToolbar() {
    apiInterface = ApiClient.getClient(getApplicationContext()).create(ApiInterface.class);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
    castComponents();
}

private void castComponents() {
    viewpager = findViewById(R.id.viewPager);
    backButton = findViewById(R.id.backButton);
    nextButton = findViewById(R.id.nextButton);
    nextButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
    GetAllDetailsOfUser();

}

@Override
public void onResume() {
    initilizeToolbar();
    super.onResume();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

public void setViewPagerData(int status) {
    FragmentManager fm = getSupportFragmentManager();
    adapter = new RegistrationPagerAdapter(fm, 0);
    viewpager.setAdapter(adapter);
    viewpager.setCurrentItem(status);
    viewpager.setPagingEnabled(false);
}

public void GetAllDetailsOfUser() {
    Call<AllProfileDetails> allDetails = apiInterface.allDetails(PrefUtils.getToken(this), PrefUtils.getID(this));
    allDetails.enqueue(new Callback<AllProfileDetails>() {
        @Override
        public void onResponse(Call<AllProfileDetails> call, Response<AllProfileDetails> response) {
            AllProfileDetails all = response.body();
            if (all != null) {
                if (all.getStatus()) {
                    Data data = all.getData();
                    setViewPagerData(data.getProfileCurrentStatus());
                    status = data.getProfileCurrentStatus();
                }
            }
        }

        public void onFailure(Call<AllProfileDetails> call, Throwable t) {
            Crashlytics.log(t.getLocalizedMessage());
        }
    });
}

@Override
public void onClick(View view) {
 switch (view.getId()) {
  case R.id.backButton:
   if (viewpager.getCurrentItem() == 0){

   }else{
       viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
   }
  break;

  case R.id.nextButton:
      if (viewpager.getCurrentItem() == 6){

      }else{
          viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
      }

  break;
 }
}

}

这是代码很好,但问题是...

当我将数据保存在 Fragment1 即 "PersonalDetailsFragment" 中时,它会移动到 fragment2 即 "AboutMeFragment"

再次单击 "AboutMeFragment" 的保存按钮时,它仅运行 "PersonalDetailsFragment" 的方法

请注意,我将片段中的 activity 按钮称为

getActivity().findViewById(R.id.backButton);
getActivity().findViewById(R.id.nextButton);

你应该有一个类似 OnSaveTapped 的界面。

public interface OnSaveTapped{
   void onSaveTapped();
}

然后让fragment实现上面的接口,ex:

public class PersonalDetailsFragment extends Fragment implements OnSaveTapped{

   public void onSaveTapped(){
       //do your business code here to save data 
   }
}

最后,在activity class:

@Override
public void onClick(View view) {
   switch (view.getId()) {
   case R.id.backButton:
   if (viewpager.getCurrentItem() == 0){

   }else{
       viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
   }
   break;

   case R.id.nextButton:
      if (viewpager.getCurrentItem() == 6){

      }else{
          viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
      }

  break;
  case R.id.button_save:
     ((OnSaveTapped)viewpager.getCurrentFragment()).onSaveTapped();
}

不要忘记为 RegistrationPagerAdapter 中的 return 当前项(片段)创建名为 getCurrentFragment() 的新方法。

public class RegistrationPagerAdapter extends FragmentPagerAdapter {

     private Fragment fragment;
     /**other lines of code*/
     public Fragment getCurrentFragment(){
        return fragment;
     }
}