[英]How to change android:drawableRight programmatically in Android
[英]How to programmatically set drawableRight on Android Edittext?
我知道在 XML 中設置 drawableRight。 但我需要以編程方式進行,因為它會根據某些條件進行更改。
您可以使用以下功能:
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.drawableRight, 0);
或者(如果你想傳遞drawable本身而不是它的ID)
editText.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context,R.drawable.drawableRight), null)
drawable位置對應的params順序為:左、上、右、下
在這里找到更多
EditText myEdit = (EditText) findViewById(R.id.myEdit);
myEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon, 0);
// where params are (left,top,right,bottom)
您還可以以編程方式設置可繪制填充:
myEdit.setCompoundDrawablePadding("Padding value");
嘗試如下:
Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
EdtText.setCompoundDrawablesWithIntrinsicBounds( 0, 0, img, 0);
編輯 :
int img = R.drawable.smiley;
EdtText.setCompoundDrawablesWithIntrinsicBounds( 0, 0, img, 0);
嘗試:
EditText editFirstname = (EditText) findViewById(R.id.edit_fname);
Drawable icUser = getResources().getDrawable(R.drawable.ic_user);
editFirstname.setCompoundDrawablesWithIntrinsicBounds(null, null, icUser, null);
然后,您可以向該特定可繪制對象添加觸摸偵聽器。
為了一次改變左右,我使用這條線。
download.setCompoundDrawablesWithIntrinsicBounds( R.drawable.ic_lock_open_white_24dp, 0, R.drawable.ic_lock_open_white_24dp, 0);
int img = R.drawable.smiley;
editText.setCompoundDrawables( null, null, img, null );
在這里解釋
setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)
將 Drawables(如果有)設置為出現在文本的左側、上方、右側和下方。 如果您不想在那里使用 Drawable,請使用 0。 Drawables 的邊界將設置為它們的內在邊界。
如果它需要可繪制的 android 圖形,那么這將起作用
Drawable dw = getApplicationContext().getResources().getDrawable(R.drawable.edit);
Button start = (Button)findViewById(R.id.buttonStart);
start.setCompoundDrawablesWithIntrinsicBounds(dw, null, null, null);
您可以使用內置函數 setCompoundDrawablesWithIntrinsicBounds() 的 editText 視圖(這里是 txview)來執行您要查找的操作
在我的代碼中,我像這樣使用它。 txview.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_arrow_drop_up,0);
txview.setCompoundDrawablesWithIntrinsicBounds(left,top,right,bottom);
et_feedback.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
}
et_feedback.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.feedback_new, 0, 0);
et_feedback.setTextColor(Color.BLACK);
}
});
使用這個隱藏 Drawable
et_feedback.setCompoundDrawablesWithIntrinsicBounds(0,0, 0, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.