以编程方式创建线性布局 android

create linearlayout programmatically android

我想创建一个新闻布局并通过数据库更新它的内容。因为我没有关于新闻数量的任何信息,所以我必须使用 For 循环来创建合适的模板。我设计了示例模板。现在我想知道,如何使用线性布局实用地创建它。

创建一个bordered_green_background.xml并将其放入其中

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <solid android:color="#A8CF8B"/>
    <stroke
        android:width="1dp"
        android:color="#051014"/>

</shape>

bordered_blue_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <solid android:color="#9CC2E6"/>
    <stroke
        android:width="1dp"
        android:color="#4C5058"/>

</shape>

bordered_blue_background2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#8EA9DC"/>
    <stroke
        android:width="1dp"
        android:color="#051014"/>
</shape>

demo_liinear_layout.xml

<TextView
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_weight="0.2"
    android:paddingTop="5dp"
    android:paddingLeft="5dp"
    android:background="@drawable/bordered_background_blue"
    android:text="Date"/>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_weight="0.75"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/bordered_background_blue_2"
        android:gravity="center_vertical"
        android:id="@+id/tvTopic"
        android:text="topic"
        android:paddingLeft="10dp"
        android:layout_weight="0.5"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/bordered_green_background"
        android:id="@+id/tvContent"
        android:text="content"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:layout_weight="0.5"/>

</LinearLayout>

然后在你的 activity 中做这样的事情

LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.demo_linear_layout, null, false);
TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);

现在用它做点什么,但老实说,用 ListView 或 RecyclerView 吧……效率很低。

注意...我在边界上失败了,但这不是问题...:)