我有一项活动,想在其中显示另一项活动。这是我的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
我怎样才能显示Activity
在内部LinearLayout
单击按钮时?
使用一种布局进行多项活动
使用以下方法为每个活动夸大布局实例setContentView
方法,通常在onCreate
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_common_layout);
}
所以使用相同的没有问题XML
不同活动的布局。
在一项活动中显示另一项活动
您可以使用Fragment
API来完成任务。请参阅完整详细信息开发者指南 http://developer.android.com/guide/topics/fundamentals/fragments.html.
-
声明这样的布局,Android 将为您创建片段:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.MyFragment"
android:id="@+id/my_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
然后创建一个MyFragment
类并在适当的时候加载它。
-
自己创建片段。不要定义Fragment
in XML
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/my_parent_layout">
</LinearLayout>
在你父母之后Activity
创建后您可以添加新的Fragment
这样:
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.my_parent_layout, fragment);
fragmentTransaction.commit();
Here MyFragment
定义如下:
public class MyFragment extends Fragment {
...
}
如果您的目标系统低于 Android 3.0,请考虑使用支持包 http://developer.android.com/sdk/compatibility-library.html为了那个原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)