【问题标题】:Replace `layout` of an <include/> tag programmatically for Android以编程方式为 Android 替换 <include/> 标记的“布局”
【发布时间】:2015-05-16 14:03:44
【问题描述】:

我想以动态/编程方式更改我的&lt;include/&gt; 标签的layout

我有一个主要的layout,我想重复使用它,但内容应该动态变化。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white_background"
    android:orientation="vertical" >
    <include
        android:id="@+id/main_container"
        layout="REPLACE_THIS" />
</android.support.v4.widget.SwipeRefreshLayout> 

上面是我正在使用的 xml,我假设您需要找到包含的 id,然后以编程方式更改它。

提前致谢。

【问题讨论】:

标签: android xml


【解决方案1】:

响应为时已晚,但经过一段时间后,我找到了一种在父布局中重用 xml 文件的简单方法。只需在您的 xml 中添加 #include 标记,然后不要忘记删除 java 类中的所有视图。然后它工作。按照上面的步骤进行操作,但不要忘记在父 xml 文件中添加包含标记。否则就不行了

【讨论】:

    【解决方案2】:

    只需更改相应 java 文件中的代码(例如 MainActivity.java):

    // Retrieve layout:
    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_container); 
    
    // Instantiate & use inflater:
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.your_layout, null);
    
    // Clear & set new views:
    mainLayout.removeAllViews();
    mainLayout.addView(layout);
    

    它对我有用。

    【讨论】:

      【解决方案3】:

      几个月前我找到了答案。您只需要使用一个 ViewStub 并为相应的充气。

      【讨论】:

      • 请注意提供解决方案,而不是像这样结束。
      • 能否请您添加解决方案?
      【解决方案4】:

      你可以这样做

      RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id. main_container); 
      LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View layout = inflater.inflate(R.layout.your_layout, mainLayout, true);
      mainLayout.removeAllView();
      mainLayout.addView(layout);
      

      在添加视图之前,您必须先删除所有视图,然后将其中的布局膨胀,如上所示

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-12
        • 2012-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多