0

我正在尝试创建一个数组,其中每个项目都有一个图像按钮,并且该图像按钮下方将是 center 的文本视图。谁能告诉我如何做到这一点。我尝试了下面的代码,但没有得到它的工作

but=new ImageButton(this);
but.setFocusableInTouchMode(true);
but.setId(1);
imbrelp= new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
rel.addView(but,imbrelp);
tv= new TextView(this);
tvrelp= new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
tvrelp.addRule(RelativeLayout.BELOW, but.getId());
tvrelp.addRule(RelativeLayout.CENTER_HORIZONTAL, but.getId());
rel.addView(tv, tvrelp);
setContentView(rel);
4

1 回答 1

0

我会避免尝试在代码中创建 RelativeLayout。对于您想做的事情来说,这将太混乱了。相反,为您的单个项目创建一个 xml 布局文件,然后为数组中的每个项目扩展它。

res/layout/main.xml 中的容器布局:

<LinearLayout
  android:id="@+id/container"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical" >

</LinearLayout>

res/layout/item.xml 中的项目布局:

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

  <ImageButton
    android:id="@+id/image_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_image" />

  <TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/image_button"
    android:layout_centerHorizontal="true"
    android:text="@string/my_text" />

</RelativeLayout>

您活动中的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
  setContentView(R.layout.main);

  ViewGroup container = (ViewGroup) findViewById(R.layout.container);

  LayoutInflater inflater = LayoutInflater.from(this);

  Item[] items = getMyArrayOfItems();
  for (Item i : items) {
    View itemView = inflater.inflate(R.layout.item, container, false);
    ImageButton button = (ImageButton) itemView.findViewById(R.id.image_button);
    TextView textView = (TextView) itemView.findViewById(R.id.text_view);

    // TODO set the text and images

    container.addView(itemView);
  }
}
于 2013-04-18T05:45:09.800 回答