【问题标题】:How to configure an inner-layout programmatically如何以编程方式配置内部布局
【发布时间】:2017-07-25 10:53:35
【问题描述】:

我在xml 中定义了一个布局,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/footer_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <!-- add views here -->            

    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app"/>

</LinearLayout>

我在我的活动中膨胀它,但 RelativeLayout 需要有 TextViews 取决于来自应用程序的数据。我怎么可能扩展它并在其中添加不同的视图?


注意:这与this question 不同,因为我试图弄清楚如何在不使用类的情况下扩展 inner 布局。

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    您可以简单地在代码中创建文本视图。然后将它们添加到您的布局中:

    RelativeLayout innerLayout= (RelativeLayout)findViewById(R.id.inner_layout);
    
    TextView textView = new TextView(this);
    
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    
    textView.setLayoutParams(p);
    
    innerLayout.addView(textView);
    

    【讨论】:

      【解决方案2】:

      Xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/footer_layout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal">
      
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id=@+id/inner_layout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center">
      
          <!-- add views here -->            
      
      </RelativeLayout>
      
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/app"/>
      
      </LinearLayout>
      

      活动

       RelativeLayout relativelayout=(RelativeLayout) findViewById(R.id.inner_layout);
       relativelayout.addview(//Add view here(one will be allowed));
      

      如果您在 RelativeLayout 中对视图进行排序,请使用规则。最好使用 LinearLayout。

      【讨论】:

        猜你喜欢
        • 2020-01-14
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 1970-01-01
        • 2022-10-19
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        相关资源
        最近更新 更多