在线性布局中通过编程方式移动布局位置

10

我有以下的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/wrapper"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_margin="10dip"
        android:weightSum="1"
        android:background="#000"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/textMessage"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight = ".9"
            android:layout_gravity="center"
            android:layout_margin="5dip"
            android:paddingLeft="10dip"
            android:background="#FFF"
            android:text="TEXT NOT SET"
            android:textColor="@android:color/white" />
        <ImageView
            android:id="@+id/thumbPhoto"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight = ".1"
            android:src="@drawable/ic_contact_default"/>
    </LinearLayout>
</LinearLayout>

我希望做的是通过编程来使我的ImageView的位置改变到textMessage的左侧。

可以在xml中通过将ImageView放置在TextView上方来实现此目的。但是我希望以编程方式实现相同的结果。

假设我在适配器中有以下内容:

public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    if (row == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.chat_item, parent, false);
    }

    wrapper = (LinearLayout) row.findViewById(R.id.wrapper);

    // How should I change the position of my ImageView ??
    wrapper.setGravity([some_condition] ? Gravity.LEFT : Gravity.RIGHT);

    return row;
}
2个回答

17

试试这样做...

ImageView imageView= (ImageView)yourLinearLayout.findViewById(R.id.thumbPhoto);
yourLinearLayout.removeViewAt(1);
yourLinearLayout.addView(imageView, 0);

通过使用这行

// How should i change the position of my ImageView ??
        wrapper.setGravity([some_condition] ? Gravity.LEFT : Gravity.RIGHT);

它没有任何效果。因为在这里您将重力应用于线性布局,该重力会使其整个内容左对齐或右对齐。


感谢您的建议,但是我无法使用addViewAt(int,view)进行应用。不过,我正在尝试使用addView(int,view,some_other_param)。 - Jeremy
1
是的,你应该使用YourLinearLayout.addView(view,index)。谢谢。我现在会接受你的回答。 - Jeremy
无论如何..你懂的..尽情享受吧。 - saa

0

http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html

请参考上述文档,了解有关如何为特定组件设置布局参数的更多详细信息。
LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
                    R.id.componentid;

btn.leftMargin = x;
btn.topMargin = y;
btn.width = width;
btn.height = height;

imageview.setLayoutParams(layoutParam);

上面的代码将展示如何使用LayoutParam。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接