0

我的要求是,我想以垂直方式动态显示三个视图(即 ImageView、TextView、TextView)。

我确实喜欢下面的程序。但它不起作用。任何人都可以帮助我。请参阅下面的代码

    for (int i = 0; i < 10; i++) {
    final RelativeLayout relativeLayout=new RelativeLayout(this);
    final ImageView imageView=new ImageView(this);
    imageView.setId(100+i);
    imageView.setBackgroundResource(R.drawable.ic_launcher);
    final RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    relativeLayout.post(new Runnable() {

        @Override
        public void run() {
            relativeLayout.addView(imageView);              
        }
    });
    final TextView textView=new TextView(this);
    textView.setId(200+i);
    String data="Click"+"\n"+"Show";
    textView.setText("click");


    newParams.addRule(RelativeLayout.BELOW, imageView.getId());
    newParams.addRule(RelativeLayout.ALIGN_LEFT, imageView.getId());
    relativeLayout.post(new Runnable() {

        @Override
        public void run() {
            relativeLayout.addView(textView, newParams);                
        }
    });
    final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    final TextView text=new TextView(this);
    text.setId(200+i);
    //String data="Click"+"\n"+"Show";
    text.setText("data");


    params.addRule(RelativeLayout.BELOW, textView.getId());
    params.addRule(RelativeLayout.ALIGN_LEFT, textView.getId());
    relativeLayout.post(new Runnable() {

        @Override
        public void run() {
            relativeLayout.addView(text, params);               
        }
    });
       linearLayout.post(new Runnable() {

        @Override
        public void run() {
            linearLayout.addView(relativeLayout);

        }
    });
    }
4

1 回答 1

0

考虑使用LinearLayout设置为垂直方向。我发现它们更容易以编程方式用于此类事情。

下面是一段示例代码:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);

linearLayout.addView(childView1);
linearLayout.addView(childView2);
linearLayout.addView(childView3);

rootView.addView(linearLayout);

childView1,childView2并将childView3垂直显示。

当然,您需要相应地修改您的代码。

于 2013-07-16T14:38:47.510 回答