如何从现有布局动态地将Imageview添加到TextView附近?

时间:2018-03-01 11:31:34

标签: android android-layout android-relativelayout

textview imageview。现在将动态生成textview。但是如何添加imageview呢?

  

的xml:

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true">

      <LinearLayout
                        android:id="@+id/ll_rl_block4_1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:layout_marginBottom="@dimen/growth_rl_block_title_table"
                        android:gravity="center_vertical"
                        android:orientation="horizontal">

                        <ImageView
                            android:id="@+id/iv_block4_1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="@dimen/growth_rl_block_title_table"
                            android:background="@drawable/dot_green" />

                        <TextView
                            android:id="@+id/tv_block4_body1_1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_vertical"
                            android:text="@string/growth_not1" />
                    </LinearLayout>
    </RelativeLayout>


    </RelativeLayout>

在MainActivity中:

public class MainActivity extends BaseActivity {

 String[] word = {"This is text1.So it should be single line", "This is text2", "This is text3"};

TextView broadcastMessage;
ImageView greenDot;

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

broadcastMessage = (TextView) findViewById(R.id.tv_block4_body1_1);
 greenDot = (ImageView) findViewById(R.id.iv_block4_1);
        for (int i = 0; i < word.length; i++) {
            broadcastMessage.append(word[i]);
            broadcastMessage.append("\n");
        }
        }

如果你看到xml,那么也有一个imageview。因此,textview现在是动态生成的,但imageviewtextview不对应。 Imageview位于左侧,对应于TextView附近。但是从xml动态生成时,在textview附近缺少点。

1 个答案:

答案 0 :(得分:1)

您可以通过添加复合drawable(左,上,右,下)来完成,如下所示:

broadcastMessage.setCompoundDrawablesWithIntrinsicBounds( getContext().getResources().getDrawable( R.drawable.smiley ), null, null, null);
相关问题