In Android development, imageview and textview are sometimes displayed as a whole, and the image and textview text of imageview can be dynamically changed. In this case, there are two methods.
Method 1: Custom composite controls:
public class CustomImageText extends LinearLayout { private ImageView iv; private TextView tv; public CustomImageText(Context context) { this(context, null); } public CustomImageText(Context context, AttributeSet attrs) { super(context, attrs); // 导入布局 LayoutInflater.from(context).inflate(R.layout.imagetext, this, true); iv = (ImageView) findViewById(R.id.iv); tv = (TextView) findViewById(R.id.tv); } /** * 设置图片资源 */ public void setImageResource(int resId) { iv.setImageResource(resId); } /** * 设置显示的文字 */ public void setText(String text) { tv.setText(text); } }
Then, reference the full path name in the layout file.
Method 2: Use the drawableleft attribute of textview, and adjust the spacing between images and texts using drawablepadding.
Drawable drawable= getResources().getDrawable(R.drawable.left); drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); tv.setCompoundDrawables(drawable,null,null,null); 或者:public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, Drawable top, Drawable right, Drawable bottom)
Use code to set drawableleft for textview