繁体   English   中英

从一个片段单击到另一个片段?

[英]Button click from one fragment to another?

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

我有一个活动和许多片段。

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

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

这是我的解决方案:

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

希望对您有所帮助!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM