我需要在下面提到的代码的文本视图之前动态设置图像,所以如何做到这一点。我的代码在下面..
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);
}
答案 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);