0

我需要在下面提到的代码的文本视图之前动态设置图像,那么如何做到这一点。我的代码如下。

if (attchStringArray.length > 0) {                      
    LinearLayout attachemntLayout = new   LinearLayout(mainContext);
    LinearLayout.LayoutParams layoutParam  = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    TextView attNameView = new TextView(mainContext);
    ImageView Ivbackground= new ImageView(mainContext);
    attNameView.setText(attchStringArray[2]);
    attachemntLayout.addView(attNameView,  layoutParam);            
    attachemntLayout.setBackgroundResource(R.drawable.bg_for_answers);
    attachmentsection.addView(attachemntLayout);
}
4

2 回答 2

1

我在您的原始代码中添加了 2 行。检查前面有注释的行。

编辑:您应该使用例如加载带有一些图像的图像视图。ImageView.setImageResource()ImageView.setImageDrawable()ImageView.setImageBitmap()

if (attchStringArray.length > 0) {

    LinearLayout attachemntLayout = new   LinearLayout(mainContext);

    // Changed width to WRAP_CONTENT
    LinearLayout.LayoutParams layoutParam  = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    TextView attNameView = new TextView(mainContext);
    ImageView Ivbackground= new ImageView(mainContext);

    // You should put some content in the ImageView
    // ...

    attNameView.setText(attchStringArray[2]);

    // I am adding the image view before the text view
    attachemntLayout.addView(Ivbackground, layoutParam);

    attachemntLayout.addView(attNameView,  layoutParam);
    attachemntLayout.setBackgroundResource(R.drawable.bg_for_answers);

    attachmentsection.addView(attachemntLayout);
}
于 2012-08-30T09:45:58.460 回答
0

试试setBackgroundDrawable()这个TextView

  yourTextView.setBackgroundDrawable(R.drwable.your_image_name);
于 2012-08-30T09:52:37.720 回答