按钮从一个片段到另一个片段?

时间:2018-01-03 18:47:30

标签: android android-fragments

我正在创建一个可以显示汽车的应用。我正在使用导航抽屉模板和RelativeLayout。

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

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

有谁知道这样做所需的代码?我听说我需要使用FragmentManager,但我不确定。

2 个答案:

答案 0 :(得分:1)

这是我的解决方案:

  1. 创建界面OnPictureOfCarClickListener

    public interface OnPictureOfCarClickListener {
       void onPictureOfCarClicked();
    }
    
  2. 使您的MainActivity实施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. 在您的HomeFragment中:

    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();
        }
    }
    
  4. 希望有所帮助!

答案 1 :(得分:0)

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

 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();
    }

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

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