在另一个文本视图下以及以编程方式在图像右侧创建textview

时间:2014-10-07 18:52:12

标签: android textview relativelayout

我以编程方式设置我的布局,因为我根据请求获得的图像填充它。我想要做的是在图像的右侧创建两个textview,在第一个下面创建第二个textview。根据我在其他答案中发现的结果,我的第二个文本视图与图像重叠并且不低于其他文本视图。

    int counter = 0;
    while(mList.size()!=counter)
    {
        RelativeLayout row = new RelativeLayout(context);
        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));            

        ImageButton imgBtn = new ImageButton(context);
        Bitmap image = getImage(mList.get(counter));
        imgBtn.setImageBitmap(image);
        imgBtn.setId(counter + 1); // Because it need to be a positive integer.
        imgBtn.setBackground(null);
        imgBtn.setPadding(0, 0, 0, 0);
        row.addView(imgBtn);

        TextView firstText = new TextView(context);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.RIGHT_OF, imgBtn.getId());
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        firstText.setLayoutParams(lp);
        firstText.setId(counter+100);
        row.addView(firstText);

        TextView secondText = new TextView(context);
        RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        lp2.addRule(RelativeLayout.BELOW,firstText.getId());
        secondText.setLayoutParams(lp2);
        row.addView(secondText);

       ++counter;
       linlayout.addView(row);
    }

1 个答案:

答案 0 :(得分:1)

使用linearLayout而不是亲属。在此你不需要设置计数器和id。而是将setTag设置为视图。使代码更具可读性。

您可以设置行布局的方向,然后无需担心其他参数来定位视图。

我没有添加代码因为我知道你可以写得很好,只需改变方法。

相关问题