1

To set the layout params (width, height and margins) or to set the LayoutParams it self to a specific Layout programatically, the layout type of the parent must be known.

Example 1

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
someLayout.setLayoutParams(lp);

Here, the someLayout type is not really need to be known. LinearLayout.LayoutParams means that the parent of someLayout is a LinearLayout.

Example 2

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)someLayout.getLayoutParams();
lp.width = LayoutParams.MATCH_PARENT;
lp.height = LinearLayout.LayoutParams.MATCH_PARENT;

The problems come when the parent type is unknown. implementing a customisable listview row layout will led to a situation with an unknown row parent. the parent that holds list item.

Example Layout for list view item

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center_horizontal|top">
       .
       .

</LinearLayout>

This go inside View returned in the getView method in Adapter class.

How to set LayoutParams to that layout with id @+id/country???

What I am really concerned about is to set margins to that layout.

4

1 回答 1

1

You can use the generic ViewGroup.LayoutParams if you don't know or can't be sure of the class of the parent. In your case, though, the parent is the ListView itself, so you can use AbsListView.LayoutParams if you need something more concrete.

Now, the problem is in any case that ListView doesn't support margins. If you want to add some space between items, you can play around with the padding of each row. If that doesn't work for you you can also add a transparent divisor to the ListView with the height you need, and maybe a horizontal margin to the ListView. Something like this:

<ListView
    ...
    android:divider="@android:color/transparent"
    android:dividerHeight="10dp"
    android:marginLeft="5dp"
    android:marginRight="5dp" />

would add a 5dp margin around every list cell.

于 2013-10-04T19:59:22.960 回答