【问题标题】:Calling setContentView() multiple times多次调用 setContentView()
【发布时间】:2010-10-25 20:53:53
【问题描述】:

有没有办法在一个 Activity 期间使用不同的 id 多次调用 setContentView(id) 以呈现不同的视图,还是我必须启动一个新的 Activity?

【问题讨论】:

    标签: android


    【解决方案1】:

    根据 Austyn 的评论,我确实设法在另一篇文章中找到了一些关于如何使用 ViewFlipper 完成此任务的指南(请参阅选中标记的最佳答案 here。)

    如果你不想使用 ViewFlipper,我找到了一个很好的例子,说明如何在同一视图中切换布局here

    XML:

    <FrameLayout 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        xmlns:android="http://schemas.android.com/apk/res/android">
        <ImageView 
            android:src="@drawable/icon"
            android:scaleType="fitCenter"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"/>
        <TextView
            android:text="Learn-Android.com"
            android:textSize="24sp"
            android:textColor="#000000"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:gravity="center"/>
    </FrameLayout>
    

    代码:

    private void SwitchLayout2() {
    RelativeLayout Layout1 = (RelativeLayout)findViewById(R.id.layout1);
    RelativeLayout Layout2 = (RelativeLayout)findViewById(R.id.layout2);
    
    // Enable Layout 2 and Disable Layout 1
    Layout1 .setVisibility(View.GONE);
    Layout2.setVisibility(View.VISIBLE);
    }
    
    private void SwitchLayout1() {
    RelativeLayout Layout1 = (RelativeLayout)findViewById(R.id.layout1);
    RelativeLayout Layout2 = (RelativeLayout)findViewById(R.id.layout2);
    
    // Enable Layout 1 & Disable Layout2
    Layout1.setVisibility(View.VISIBLE);
    Layout2.setVisibility(View.GONE);
    }
    

    【讨论】:

    • 您真的应该使用ViewFlipper 来执行此操作,而不仅仅是更改每个View 的可见性
    • @AustynMahoney,很高兴知道为什么最好使用 ViewFlipper 而不是 glenviewjeff 所描述的方法。
    • 既然 Android 已经提供了一种非常简单的方法来完成这件事,为什么还要重新发明轮子呢?当您想将其扩展到 3 个布局或 18 个布局时会发生什么?如果您使用了ViewFlipper,那就太简单了,如果您维护该代码库的运气不佳。
    • 示例链接正在建设中。
    • 这将导致不必要的内存负载。每个布局都将被创建并保存在内存中,当您使它们可见/不可见时,它们只会显示在隐藏状态。比如说,如果你有 5 个布局,你会不必要地加载很多 UI 组件,这就是为什么这是一个糟糕的设计。
    【解决方案2】:

    不,你不能轻易地多次调用它。您要么需要完全移除所有视图,然后扩展新布局,要么使用ViewFlipper(或FrameLayout)在不同视图之间切换。

    顺便说一句,这个问题以前有人问过,虽然我没能立即找到。

    【讨论】:

      【解决方案3】:

      你可以从你的活动中试试这个:

      getWindow().addContentView(View, ViewGroup.LayoutParams);
      

      两个内容视图将一个在另一个之上。但是,没有直接的方法可以删除以这种方式添加的某个视图。

      另请注意,在最后一次调用后调用setContentView,将删除之前添加的所有内容视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2014-04-09
        相关资源
        最近更新 更多