繁体   English   中英

Android:添加左可绘制对象时如何使按钮的修复文本

[英]Android: How to make fix text of the button when add left drawable

我已经创建了自定义视图。 在我的课堂上,我创建一个按钮:

button = new AppCompatButton(getContext());
LayoutParams button_params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
button_params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
button.setLayoutParams(button_params);
button.setText(TextUtils.isEmpty(progressText) ? "Button" : progressText);
button.setGravity(Gravity.CENTER);
button.setOnClickListener(v -> {
    progressBar.setVisibility(VISIBLE);
});
addView(button);

我向此按钮添加了一个drawable,如下所示:

   if (isDone) {
        progressBar.setVisibility(GONE);
        Drawable drawable = getResources().getDrawable(progressIconSuccess);
        drawable.setBounds(0, 0, 100, 100);
        button.setCompoundDrawables(drawable, null, null, null);
    } 

但是,当将drawable添加到按钮时,按钮文本向右移动:

在添加drawable之前:

在此处输入图片说明

在drawable之后添加:

在此处输入图片说明

我不想将按钮文本移到右边。 我要保持固定而不改变其位置。我该怎么做?

我以这种方式使用自定义视图:

<com.tazik.progressbutton.ProgressButton
    android:id="@+id/pb_button"
    android:layout_width="150dp"
    android:layout_height="70dp"
    app:progress_height="30"
    app:progress_width="30"
    app:progress_text = "Register"
    app:progress_iconfail="@drawable/ic_fail"
    app:progress_iconSuccess="@drawable/ic_done"/>

使用新的MaterialIconButton

按钮XML代码

 <com.google.android.material.button.MaterialButton
    android:id="@+id/btn"
    style="@style/Widget.MaterialComponents.Button.Icon"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Icon Button"
     />

活动代码:

public class MainActivity extends AppCompatActivity {

    MaterialButton iconButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);

        iconButton=findViewById(R.id.btn);
        iconButton.setIcon(R.drawable.your_icon);
        iconButton.setIconGravity(MaterialButton.ICON_GRAVITY_START);
    }
}

progressBar.setVisibility(GONE)更改为progressBar.setVisibility(INVISIBLE)

顾名思义,当您将可见性设置为GONE ,视图“物理上”消失了-它不存在,而使用INVISIBLE则它仍然存在,但只是没有绘制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM