I'm retrieving data from WebService and I use a custom adapter ArrayAdapter
to populate my listView
. For each row, I have to set a left or right margin depending webservice return. So my idea was using this following code :
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 0, 0, 0); // left margin
holder.mainContainer.setLayoutParams(layoutParams); // Here is the problem
mainContainer is a LinearLayout
In getView
method I use the view hodler pattern
MessageHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(MessagesActivity.this).inflate(R.layout.thread_activity_listview_item, null);
holder = new MessageHolder();
holder.mainContainer = (LinearLayout) convertView.findViewById(R.id.main_container);
convertView.setTag(holder);
} else {
holder = (MessageHolder) convertView.getTag();
}
Here is my xml
for a row :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rounded_left_corner_discussion_on"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical" />
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:gravity="center_vertical"
android:textColor="@android:color/black"
android:textSize="16sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:orientation="horizontal" >
<TextView
android:id="@+id/updated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp" />
</LinearLayout>
But with this code, I have the following error :
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
I precise, I can't use padding in my situation. Moreover if I use AbsListView.LayoutParams
instead of LinearLayout.LayoutParams
, I can't set margin anymore.
Thanks