【问题标题】:Programmatically include layout in middle以编程方式在中间包含布局
【发布时间】:2015-08-24 00:00:09
【问题描述】:

如何以编程方式将布局包含在另一个布局的特定位置?

例如,如果我有这样的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/some_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, world!"
            />

        // INCLUDE HERE

    </LinearLayout>

</LinearLayout>

如何在父布局的特定位置包含以下布局(以编程方式)?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/some_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

</LinearLayout>

【问题讨论】:

    标签: android android-layout android-fragments android-activity android-xml


    【解决方案1】:

    将 id 添加到垂直方向的线性布局(例如:主视图)。您的动态视图的代码如下。

    LinearLayout masterView = (LinearLayout)findViewById(R.id.masterView);
    
            LinearLayout childView = new LinearLayout(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            childView.setLayoutParams(lp);
    
            LinearLayout childToChildView = new LinearLayout(this);
            childToChildView.setLayoutParams(lp);
    
            ImageView imageView = new ImageView(this);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            imageView.setLayoutParams(layoutParams);
            imageView.setId(View.generateViewId());//some integer number
    
            childToChildView.addView(imageView);
    
            childView.addView(childToChildView);
    
            masterView.addView(childView);
    

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 2018-10-22
      • 2017-03-13
      • 2011-03-12
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多