Android:需要先将Image设置为TextView

时间:2012-08-30 09:27:58

标签: android

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

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);
}

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

setBackgroundDrawable()

试试这个TextView
  yourTextView.setBackgroundDrawable(R.drwable.your_image_name);