Как добавить контент в программно сгенерированный линейный макет - PullRequest
0 голосов
/ 23 марта 2019

Мне нужно динамически генерировать несколько плиток (вертикальный 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>
...