Android动态添加按钮时出现问题

时间:2016-02-07 18:10:43

标签: java android dynamic

所以,我正在尝试为一个arraylist中的每个项目添加滚动视图的按钮。但是程序运行得很好,按钮似乎没有显示出来。有人可以告诉我,我可能做错了什么,或者我可能会错过什么?

以下是我尝试添加按钮的代码:

public void setScreen(){

    RelativeLayout rl = (RelativeLayout) findViewById(R.id.invScr);
    RelativeLayout layout = new RelativeLayout(this);
    HashMap<String, ArrayList<ItemBase>> items = hero.getStuff();
    ScrollView sv = new ScrollView(this);

    for (Entry<String, ArrayList<ItemBase>> entry : items.entrySet()){
         String key = entry.getKey();
         ArrayList<ItemBase> value = entry.getValue();

         for (ItemBase item: value){
             LayoutParams rpram = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
             bt.add(new Button(this));
             bt.get(i).setText(key);
             bt.get(i).setLayoutParams(rpram);
             layout.addView(bt.get(i));
             invn.add(item);
             bt.get(i).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    j = i;

                }
            });
             i++;
         }
    }
    rl.addView(sv);
    sv.addView(layout);

}

这是我之前的其他一些代码

ArrayList<ItemBase> invn = new ArrayList<ItemBase>();
ArrayList<Button> bt = new ArrayList<Button>();
int i = 0;
int j = 0;

这是布局的xml文件,如果它是相关的

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/invScr"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="toCharacter"
        android:text="Back" />



    <TextView
        android:id="@+id/infoDis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/eatbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="useItem"
        android:text="Use" />

</RelativeLayout>

0 个答案:

没有答案