在 LinearLayout 中動態創建 TextView 和 ImageButton,使圖標顯示在文本左側(或右側)。
TextView textView = new TextView(context);
textView.setText("文本內容");
// 設置左側圖標(自動處理間距、對齊)
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);
// 可調整間距
textView.setCompoundDrawablePadding(8);
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.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 靈活可控。