Change Button Drawable Programmatically [duplicate]

喜欢而已 提交于 2019-12-10 10:07:44

问题


I have a button with drawable left:

<Button
    android:id="@+id/post_feeling_btn"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp"
    android:drawableLeft="@drawable/feeling_btn"
    android:gravity="left|center_vertical"
    android:textColor="@color/gray"
    android:text="Sentimento"/>

In my on resume method, I change the button's text programmatically:

Button setFeeling;
FeelingButton selectedFeeling;

@Override
public void onResume() {
    super.onResume();
    selectedFeeling = ((FeedActivity)getActivity()).getSelectedFeeling();
    if(selectedFeeling != null){
        setFeeling.setText(selectedFeeling.getFeeling());
    }
}

Is there a way to change my drawable left and set the image in the same method, using the image I have in my selectedFeeling object? I'm looking for something like:

setFeeling.setDrawable();

回答1:


try something like this: for drawableLeft

int imgResource = R.drawable.your_drawable;
setFeeling.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
setFeeling.setCompoundDrawablePadding(8);     //for padding

Thanks to the Answer Here also.




回答2:


You are almost there: setBackgroundResource

setFeeling.setBackgroundResource(R.drawable.appIcon);


来源:https://stackoverflow.com/questions/42772632/change-button-drawable-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!