Tuesday 18 April 2017

Android dynamically creating a list using linearlayout

 LinearLayout specListLayout = (LinearLayout) findViewById(R.id.specList);//main layout
        for(int x=0;x<10;x++){
            View child = getLayoutInflater().inflate(R.layout.row, null);
            TextView colOne = (TextView) child.findViewById(R.id.colOne);
            TextView colTwo = (TextView) child.findViewById(R.id.colTwo);

            colOne.setText("Key"+x);
            colTwo.setText("Value"+x);

            if(x%2==0){
                colOne.setBackgroundColor(Color.parseColor("#CCCCCC"));
                colTwo.setBackgroundColor(Color.parseColor("#FFFFFF"));
            }else{
                colOne.setBackgroundColor(Color.parseColor("#FFFFFF"));
                colTwo.setBackgroundColor(Color.parseColor("#CCCCCC"));
            }
            specListLayout.addView(child);
        }

row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:weightSum="10">

    <TextView
        android:id="@+id/colOne"
        android:layout_width="0dp"
        android:layout_weight="5"
        android:gravity="center_vertical"
        android:layout_height="50dp"
        android:padding="5dp"
        android:text="testing"
        android:textColor="@color/black"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/colTwo"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="5"
        android:background="#CCCCCC"
        android:gravity="center"
        android:padding="5dp"
        android:text="testing2"
        android:textColor="@color/black" />
</LinearLayout>

No comments:

Post a Comment