首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 代碼動態添加 ImageView 到 TextView 右側

     編輯:程式設計綜合問答

需求描述

在 LinearLayout 中動態創建 TextView 和 ImageButton,使圖標顯示在文本左側(或右側)。

方案一:使用 TextView 複合繪製(推薦,最簡單)


TextView textView = new TextView(context);
textView.setText("文本內容");
// 設置左側圖標(自動處理間距、對齊)
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
// 可調整間距
textView.setCompoundDrawablePadding(8);

方案二:水平 LinearLayout 包裹


LinearLayout container = new LinearLayout(context);
container.setOrientation(LinearLayout.HORIZONTAL);
container.setGravity(Gravity.CENTER_VERTICAL); // 垂直居中

ImageButton icon = new ImageButton(context);
icon.setImageResource(R.drawable.icon);
icon.setLayoutParams(new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

TextView text = new TextView(context);
text.setText("文本內容");
text.setLayoutParams(new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

// 順序決定左右:先加 icon 再加 text → icon 在左
container.addView(icon);
container.addView(text);

parentLayout.addView(container);

方案三:RelativeLayout 規則(較繁瑣)


RelativeLayout.LayoutParams iconParams = new RelativeLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
iconParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
iconParams.addRule(RelativeLayout.CENTER_VERTICAL);

RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textParams.addRule(RelativeLayout.RIGHT_OF, iconId); // 需為 icon 分配 ID
textParams.addRule(RelativeLayout.CENTER_VERTICAL);

總結

文本旁加圖標首選 TextView.setCompoundDrawablesWithIntrinsicBounds(),單行文本最簡潔;複雜佈局用水平 LinearLayout 靈活可控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved