For example,to create alternate layout in ListView which uses different alternate color :
<LinearLayout
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
I can set the color at the getView method:
MyActivity.this.findViewById(R.id.view1).setBackgroundColor(position%2=0?Color.RED.Color.BLUE);
But I would rather copy and place same layout file:
row_style1.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
row_style2.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000FF"
android:orientation="vertical">
<TextView
android:id="@+id/textview_publish_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TextView>
</LinearLayout>
and then inflate different layouts at the getView method:
view=LayoutInflater.from(MyFragment.this.getActivity()).inflate(i%2==0?R.layout.row_style1:R.layout.row_style2,null);
I think it is more maintainable because it separate more style concerns from code, especially when there is more different styles between different parts, eg:
findViewById(R.id.view1).setBackgroundColor(position%2=0?Color.RED.Color.BLUE);
findViewById(R.id.view2).setBackgroundColor(position%2=0?Color.YELLOW.Color.GREEN);
which can be simplified by inflating different layouts. Is it good or bad practice to do this?