我正在尝试使按钮上的文本和图像动态显示-文本需要显示在左侧,图像需要显示在右侧。举个例子,这是我想要的一张图片。
在StackOverflow上搜索了其他几个示例之后,在我的活动中尝试了以下代码,但似乎无法正常工作。有人可以建议我做错了什么吗?
代码:
btn.setTextColor(Color.parseColor("#000000"));
btn.setText("SomeText");
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mediumTextSize);
Drawable icon= getApplicationContext().getResources().getDrawable( R.drawable.cal);
icon.setBounds(0, 0, 0, 0); //Left,Top,Right,Bottom
btn.setCompoundDrawablesWithIntrinsicBounds( null, null, icon, null );
答案 0 :(得分:0)
我注意到在其他对象上使用图像时,图像的大小非常重要-当我将图像调整为较小的尺寸时,我的代码可以正常工作。...
调整图像大小后,我之前尝试的相同代码对我有用...
Button btn = new Button(this);
btn.setTextColor(Color.parseColor("#000000"));
btn.setText("SomeText");
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mediumTextSize);
btn.setGravity(Gravity.CENTER | Gravity.LEFT);
Drawable icon= getApplicationContext().getResources().getDrawable(R.drawable.cal);
btn.setBackgroundResource(R.drawable.light_bg);
icon.setBounds(0, 0, 0, 0); //Left,Top,Right,Bottom
btn.setCompoundDrawablesWithIntrinsicBounds( null, null, icon, null);
谢谢大家的帮助和建议!
答案 1 :(得分:0)
尝试一下
btn.setText("Some Text");
btn.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
btn.setGravity(Gravity.CENTER | Gravity.LEFT);
Drawable myDrawable =
getResources().getDrawable(R.drawable.ic_cancel_black_24dp);
btn.setCompoundDrawablesWithIntrinsicBounds(null,null,myDrawable,null);