如何将内容添加到以编程方式生成的linearlayout

时间:2019-03-22 23:05:01

标签: android android-layout android-linearlayout

我需要动态生成一些图块(垂直LinearLayout)。在每个图块的内部,左侧都有一个图像,右侧有一些文本,例如温度,湿度和状态。图像,文本和图块的数量可以在运行时更改。

我设法生成了图块,但没有找到有关如何向其添加内容的解决方案。有人可以告诉我正确的方法吗?

ScrollingActivity.java

public class ScrollingActivity extends AppCompatActivity {
    private LinearLayout myLayout;
    Context ctx;
    DynamicLayout DynLay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        myLayout = (LinearLayout) findViewById(R.id.linLayout);
        DynLay = new DynamicLayout(ctx);

        // Add some Tiles
        for(int i=0; i<10; i++) {
            myLayout.addView(DynLay.addTile(getApplicationContext(), "Tile " + i));
        }
    }

DynamicLayout.java

public class DynamicLayout {
    Context ctx;

    public DynamicLayout(Context ctx){
        this.ctx = ctx;
    }

    public LinearLayout addTile(Context context, String text){
        // Tile
        LinearLayout.LayoutParams LinParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 150);
        LinParams.setMargins(0, 3, 0, 3);
        LinearLayout Tile = new LinearLayout(context);
        Tile.setLayoutParams(LinParams);
        Tile.setOrientation(LinearLayout.VERTICAL);
        Tile.setBackgroundColor(Color.rgb(208,226,217));

        // Content of Tile

        // ... HOW TO ADD SOME CONTENT???

        return Tile;
    }

content_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scroll"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".ScrollingActivity"
    tools:showIn="@layout/activity_scrolling">

    <LinearLayout
        android:id="@+id/linLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:columnCount="3"
        android:orientation="vertical"
        android:padding="10dp">

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

0 个答案:

没有答案