如何在 LinearLayout 中的同一行设置 Imageview 和 Textview

How can I set Imageview and Textview on same line in LinearLayout

我想在 LinearLayout 中将 Imageview 和 Textview 设置在同一行,但 Imageview 总是高于 Textview。

这是我的代码:

String b[] = cacBuocThucHien.split("#");
for (int j = 0; j < b.length; j++) {
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(30,30);
    lp.setMargins(50, 0, 0, 0);
    ImageView img = new ImageView(RecipesDetailActivity.this);
    TextView tv = new TextView(RecipesDetailActivity.this);
    img.setLayoutParams(lp2);
    img.setImageResource(R.mipmap.testic);
    tv.setLayoutParams(lp);
    tv.setText(b[j] + "\n");
    layoutHuongDan.addView(img);
    layoutHuongDan.addView(tv);
}

您可以使用它来将图像放在一行中。它适用于所有类型的布局。希望这会对你有所帮助

  <LinerLayout>     
   <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
  <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
   ....... // Put how many TextViews you want

 <TextView
        android:id="@+id/textn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 </LinerLayout>

如果您只想在设置文本后显示这些文本视图,您可以将可见性设置为消失。 现在在你的 activity 中创建一个这样的文本视图 ID 数组...

public static int[] textRows = {R.id.text1, R.id.text2, ........ R.id.textn};

然后使用 for 循环初始化它们并像这样设置文本和图像

   TextView[] allTexts = new TextView[n];
   for (int i = 0; i < n; i++) {
        allTexts[i] = (TextView) findViewById(textRows[i]);
        allTexts[i].setText("your text");
        allTexts[i].setCompoundDrawables(left_image, null, null, null); 
    }

它会起作用的。试试看

设置 textview drawable left 不需要额外的 imageview

android:drawableLeft="@drawable/img"

如果你只想在 TextView 旁边显示一个图标,我认为你应该考虑使用 drawable icon feature of TextView

tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

但是如果您坚持使用两个并排的视图,在这种情况下使用 layout gravity 会很有用。

lp.gravity= Gravity.CENTER_VERTICAL;

如果您只想显示 TextViewImageView.. 请在 TextView 本身中设置 CompounDrawable..

但是,要以编程方式在 LinearLayout 中并排显示两个视图,请尝试设置 orientation=horizontal,请查看 this link