如何在一个单一的活动以显示从第一个片段第二个片段与 [英] How to show second fragment from first fragment with in a single activity

查看:286
本文介绍了如何在一个单一的活动以显示从第一个片段第二个片段与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只开发针对平板电脑一个简单的Andr​​oid应用程序,并采用了android 4.0。我的应用程序有主屏类似如下:

I am developing a simple android app only for tablets and using android 4.0. My application have the main screen like as follow:

在OnCreate()主要活动的我正在使用的main.xml中添加片段A以下code:

Oncreate() of Main Activity I am adding Fragment A in the main.xml using following code:

FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment imageFragment = new ImageFragment();
ft.replace(R.id.fragment_container, imageFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

这个片段只是一个只有一个图像视图是点击。现在我想,当用户点击图片查看然后又片段(片段B)应该调用它替换图像视图。该片段B有一个VideoView它播放视频。

This fragment A just have only a Image view which is clickable. Now I want that when user click on Image view then another fragment (Fragment B) should call and it replace the image view. The Fragment B have a VideoView which play the video.

所以我的第二个屏幕应该像如下:

So My second screen should be like as follow:

我的问题是我不流汗的如何从第一个调用第二个片段,在主屏幕上的活动?

My problem is I am not gettting "How to call second fragment from the first one with in main screen activity?"

我可以用不同的活动,但我并不想这样做,只是想利用片段来运行这个。

I can use different activities but I do not want to do so and just want to run this using fragments.

请指引我。

推荐答案

这是最简单的方法:

1)在 YourActivity 创建一个方法:

1) Inside YourActivitycreate a method:

public void goToSecondFragment(){}
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment secondFragment = new SecondFragment();
    ft.replace(R.id.fragment_container, secondFragment);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(null);
    ft.commit();
}

2)你的第一个片段,当你要替换它,请致电:

2) In your first fragment, when you want to replace it, call:

YourActivity activity = (YourActivity) getActivity();
activity.goToSecondFragment();

这篇关于如何在一个单一的活动以显示从第一个片段第二个片段与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆