按钮从一个片段单击到另一个片段



我正在创建一个显示汽车的应用程序。我正在使用导航抽屉模板和相对布局。

我有一个活动和一些片段。

在我的activity_main页面(用户首次加载应用程序时看到的页面(中,我有一个带有汽车图片的片段(HomeFragment(。我希望能够点击汽车,它将我带到另一个片段,在那里我可以放置同一辆车的更多图像。

有谁知道执行此操作所需的代码?我听说我需要使用FragmentManager,但我不确定。

这是我

的解决方案:

  1. 创建接口OnPictureOfCarClickListener

    public interface OnPictureOfCarClickListener {
       void onPictureOfCarClicked();
    }
    
  2. 让你的主活动实现OnPictureOfCarClickListener。这将需要您@Override onPictureOfCarClicked()方法:

    @Override
    public void onPictureOfCarClicked() {
       // this method will call when you click to the picture of car in your HomeFragment.
      // I will named fragment show more images is MoreCarFragment
      MoreCarFragment fragment = new MoreCarFragment();
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
      transaction.replace(R.id.fragmentContainer, fragment);
      transaction.commit();
    }
    
  3. 在您的主页片段中:

    public class HomeFragment extends Fragment {
       OnPictureOfCarClickListener mCallback;
      @Override
      public void onAttach(Activity activity) {
         super.onAttach(activity);
         // This makes sure that the container activity has implemented
         // the callback interface. If not, it throws an exception
         try {
           mCallback = (OnPictureOfCarClickListener) activity;
        } catch (ClassCastException e) {
          throw new ClassCastException(activity.toString()
                + " must implement OnPictureOfCarClickListener");
        }
        // when you click to the picture of car
        public void onPictureOfCarClick(View view) {
          mCallback.onPictureOfCarClicked();
        }
    }
    

希望对您有所帮助!

按照我在项目中使用的示例,案例中的每个项目都是我的布局中的一个图像。

 switch (v.getId()) {
        case R.id.bottom_navigation_help:
           selectedFragment = HelpFragment.newInstance();
            break;
        case R.id.bottom_navigation_start:
           selectedFragment = WalletFragment.newInstance();
           break;
        case R.id.bottom_navigation_client:
           selectedFragment = CustomerListFragment.newInstance();
            break;
        case R.id.bottom_navigation_statistics:
           selectedFragment = StatisticsFragment.newInstance();
            break;
        case R.id.bottom_navigation_comunication:
            walletPresenter.checkCommunicationStep();
            break;
    }
    if (selectedFragment != null) {
        hideProgressDialog();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragmentContent, selectedFragment);
        transaction.commit();
    }

您还需要将其添加到每个 1 个片段中

 @NonNull
public static Fragment newInstance() {
    return new ClientFragment();
}

最新更新