2017-01-16 1 views
0

배경 drawable 이미지를 가지고있는 relativelayout으로 설정하려고합니다. 나는 setBackground를 사용하고 있으며 int가 아닌 drawable을 요구한다. 나는 드로어 블 (drawable)을 줄 수 있으며, 스틸은 나에게 오류를 준다. 여기 내 코드의 섹션.relativelayout의 배경 이미지 설정 시도

rl.setBackground(R.drawable.loginbackground3); 

이것은 내가 얻는 오류입니다.

setBackground (android.graphics.drawable.Drawable) in View cannot be applied to (int). 

도와주세요 매우 혼란?

답변

1

이 시도 : 당신이 지원 라이브러리를 사용하는 경우 당신이 그렇게 같은 getDrawable의 중단을 해결할 수

Drawable background = rl.getContext().getResources().getDrawable(R.drawable.loginbackground3); 
rl.setBackground(background); 

주 이런 경우에는 빌드 버전을 확인해야합니다 (낮은 버전을 빌드하는 경우).

private Drawable getDrawable(int id) { 
    final int sdk = android.os.Build.VERSION.SDK_INT; 
    if (sdk >= android.os.Build.VERSION_CODES.LOLLIPOP) { 
    return ContextCompat.getDrawable(getContext(), id); 
    } else { 
    return getContext().getResources().getDrawable(id); 
    } 
} 

다음 :

이 때문에 안드로이드 자체에서 라이브러리의 불일치
RelativeLayout r1 = (RelativeLayout) findViewById(R.id.relativelayout1); 
r1.setBackgroundResource(R.drawable.sample); 
+0

rl.setBackgroundResource (R.drawable.loginbackground3); 그리고 나는 어떤 오류도 가지지 않지만 작동하지 않습니다. 아무 반응이 없습니다. 배경이 바뀌지 않습니다. –

1

해당 드로어 블 참조를 사용하여 드로어 블을로드해야합니다. 당신이 원하는 경우

rl.setBackgroundResource(R.drawable.loginbackground3); 

또는 :

Drawable background = ContextCompat.getDrawable(rl.getContext(), R.drawable.loginbackground3); 
rl.setBackground(background); 
+0

임 라인에 오류가 점점 :.. 드로어 블 배경 = rl.getContext()의 GetResources() getDrawable (R.drawable.loginbackground3를); 오류는 다음과 같습니다. android.content.Context android.widget.RelativeLayout.getContext() 'null 객체 참조 –

0

은 당신의 레이아웃을 가정 할 relativelayout1 이름 // , 메소드 생성 setBackgroundView :

private void setBackgroundView(View v, int drawable_Rid) { 
    Drawable background = getDrawable(drawable_Rid); 
    final int sdk = android.os.Build.VERSION.SDK_INT; 
    if (sdk >= android.os.Build.VERSION_CODES.JELLY_BEAN) { 
    v.setBackground(background); 
    } else { 
    v.setBackgroundDrawable(background); 
    } 
} 

그리고 마지막으로이 같은 당김 이름으로 setBackgroundView 전화 :

setBackgroundView(rl, R.drawable.loginbackground3); 
0

, 첫째, 당신은 방법 getDrawable을 만들어야합니다

final int sdk = android.os.Build.VERSION.SDK_INT; 
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { 
    rl.setBackgroundDrawable(getResources().getDrawable(R.drawable.loginbackground3)); 
} else { 
    rl.setBackground(getResources().getDrawable(R.drawable.loginbackground3)); 
}