在游标中更改bindview中的布局参数 - Android

时间:2014-07-26 15:15:47

标签: android

我有以下XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/background"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    android:paddingRight="4dip" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="32dip"
        android:layout_height="32dip"
        android:layout_marginLeft="4dip"
        android:src="@drawable/test_imag" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/imageView1" />

</RelativeLayout>

以及游标中的以下bindView

public void bindView(View view, Context context, Cursor cursor) {

    wrapper = (RelativeLayout) view.findViewById(R.id.background);

    TextView tview2 = (TextView) view.findViewById(R.id.text2);

    ImageView imgview = (ImageView) view.findViewById(R.id.imageView1);

    tview2.setText("Test text");

    if (cursor.getPosition() % 2 == 0) {

        tview2.setBackgroundResource(R.drawable.bubble_left);   

    } else {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        tview2.setBackgroundResource(R.drawable.bubble_right);

        params.addRule(RelativeLayout.LEFT_OF, R.id.imageView1);

        tview2.setLayoutParams(params);

        wrapper.setGravity(Gravity.RIGHT);
    }

}

我正在尝试与图像进行气泡聊天,IF部分很好,图像位于屏幕的右侧,文本位于屏幕的左侧。 在else部分,我将重力设置在右边,并添加一个规则,将tview2设置在图像的左侧。

上面的结果使图像移到了屏幕的右侧但是tview2已经消失了,我做错了什么?

1 个答案:

答案 0 :(得分:0)

你需要为 imageview 指定params,因为你最初在xml中声明它相对于textview。

imageparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

结果将是这样的。

else {
        RelativeLayout.LayoutParams imageparams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        imageparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        imgview.setLayoutParams(imageparams);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        tview2.setBackgroundResource(R.drawable.bubble_right);

        params.addRule(RelativeLayout.LEFT_OF, R.id.imageView1);

        tview2.setLayoutParams(params);

        wrapper.setGravity(Gravity.RIGHT);
    }