在 android 中以编程方式在按钮上添加文本和图像

Adding a text and image on a button programmatically in android

我正在尝试让按钮上的文本和图像动态显示 - 文本需要出现在左侧,图像需要出现在右侧。举个例子,这是我想要得到的图像。

在 Whosebug 上搜索了几个其他示例后,在我的 activity 中尝试了以下代码,但它似乎不起作用。任何人都可以建议我做错了什么吗?

代码:

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

我注意到在其他对象上使用图像时,图像的大小非常重要 - 当我将图像调整为较小的尺寸时,我的代码运行良好....

调整图像大小后,我之前尝试的相同代码对我有用...

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

感谢大家的帮助和建议!

试试这个

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