将一个Activity分割成两部分,每个部分显示一个自定义View

最近刚开始学习Android开发,在练习写一个自定义View时就想能否把两个自定义View塞到一个Activity里。由于之前看的一直是SetContentView,也就没能实现,后来发现AddView可以实现,在这里记录一下,怕自己以后忘记了

布局文件:

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:id="@+id/zone1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        
    </LinearLayout>
    <LinearLayout android:id="@+id/zone2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        
    </LinearLayout>
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个Activity转换一个View显示,可以按以下步骤操作: 1. 在Activity中,创建一个布局文件,用来显示界面上的各个控件和视图。 2. 在Activity中重写onCreateView()方法,在该方法中加载布局文件,生View对象并返回。 3. 在Activity中获取FragmentManager对象,并通过调用FragmentManager.beginTransaction()方法创建一个FragmentTransaction对象。 4. 在FragmentTransaction对象中,使用add()方法将生View对象添加到要显示它的布局容器中。 5. 调用commit()方法提交事务,完Activity转换View显示的操作。 以下是一个简单的示例代码: ``` public class MyActivity extends Activity { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 加载布局文件 View view = inflater.inflate(R.layout.my_layout, container, false); // 返回生View对象 return view; } public void showAsView(ViewGroup container) { // 获取FragmentManager对象 FragmentManager fragmentManager = getFragmentManager(); // 创建FragmentTransaction对象 FragmentTransaction transaction = fragmentManager.beginTransaction(); // 将生View对象添加到要显示它的布局容器中 transaction.add(container.getId(), this); // 提交事务,完Activity转换View显示的操作 transaction.commit(); } } ``` 在代码中,MyActivity继承自Activity类,并重写了onCreateView()方法,用来加载布局文件并生View对象。同时,还提供了一个showAsView()方法,用来将该Activity转换View显示在指定的布局容器中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值