programing

Android에서 프로그래밍 방식으로 배경 그리기 설정 방법

prostudy 2022. 7. 27. 21:46
반응형

Android에서 프로그래밍 방식으로 배경 그리기 설정 방법

배경을 설정하려면:

RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

그게 최선의 방법인가요?

layout.setBackgroundResource(R.drawable.ready);정답입니다.
또 다른 방법은 다음을 사용하는 것입니다.

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
    layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}

하지만 당신이 큰 이미지를 로드하려고 하기 때문에 문제가 발생하는 것 같습니다.
다음은 대용량 비트맵을 로드하는 좋은 튜토리얼입니다.

갱신:
getDrawable(int)은 API 수준 22에서 사용되지 않습니다.


getDrawable(int )는 API 레벨 22에서 폐지되었습니다.대신 지원 라이브러리에서 다음 코드를 사용해야 합니다.

ContextCompat.getDrawable(context, R.drawable.ready)

ContextCompat.getDrawable의 소스 코드를 참조하면 다음과 같은 정보가 나타납니다.

/**
 * Return a drawable object associated with a particular resource ID.
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
 * drawable will be styled for the specified Context's theme.
 *
 * @param id The desired resource identifier, as generated by the aapt tool.
 *            This integer encodes the package, type, and resource entry.
 *            The value 0 is an invalid identifier.
 * @return Drawable An object that can be used to draw this resource.
 */
public static final Drawable getDrawable(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return ContextCompatApi21.getDrawable(context, id);
    } else {
        return context.getResources().getDrawable(id);
    }
}

ContextCompat 상세

API 22에서는getDrawable(int, Theme)getDrawable(int) 대신 메서드를 지정합니다.

갱신:
지원 v4 라이브러리를 사용하는 경우 모든 버전에 대해 다음 사항으로 충분합니다.

ContextCompat.getDrawable(context, R.drawable.ready)

앱 build.gradle에 다음 항목을 추가해야 합니다.

compile 'com.android.support:support-v4:23.0.0' # or any version above

또는 다음과 같은 API에서 Resource Compat을 사용합니다.

import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

이것을 시험해 보세요.

layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

및 API 16의 경우 <:

layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
RelativeLayout relativeLayout;  //declare this globally

이제 onCreate, onResume와 같은 함수 내에서

relativeLayout = new RelativeLayout(this);  
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this

minSdkVersion 16과 targetSdkVersion 23을 사용하고 있습니다.
다음은 나에게 효과가 있습니다.

ContextCompat.getDrawable(context, R.drawable.drawable);

사용하는 대신:

layout.setBackgroundResource(R.drawable.ready);

사용방법:

layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

getActivity()액티비티 사용에서 콜하는 경우 fragment로 사용됩니다.this.

이미지의 배경을 설정할 수도 있습니다.

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

AndroidX를 사용하는 경우 다음을 사용해야 합니다.

AppCompatResources.getDrawable(context, R.drawable.your_drawable)

위에 기재된 메서드는 권장되지 않습니다.

현재 배경이 그리기 가능한 폴더에 있는 경우 프로젝트에서 그리기 가능한 폴더에서 그리기 가능한 nodpi 폴더로 이미지를 이동해 보십시오.이것은 나에게 효과가 있었습니다.그렇지 않으면, 스스로 이미지의 사이즈를 변경하는 것 같습니다.

butterknife를 사용하여 그리기 가능한 리소스를 클래스 맨 위에 추가하여 변수에 바인딩합니다(메서드 이전).

@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;

다음 중 하나의 메서드에

layout.setBackground(background);

그것만 있으면 돼

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
     layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
     layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
     layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

이거 먹어봐.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

해 보다ViewCompat.setBackground(yourView, drawableBackground)

setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

다음 코드를 사용해 보십시오.

Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);

스플래시스크린 조각이 4개 있습니다.이 코드로 fragment를 변경하여 배경을 변경할 수 있습니다.

screen_main=(ConstraintLayout)view.findViewById(R.id.screen_main);
    screen_main.setBackground(getContext().getResources().getDrawable(R.color.bg_screen1));

app/res/your_xml_layout_file.xml 내부

  1. 부모 레이아웃에 이름을 할당합니다.
  2. MainActivity로 이동하여 findViewById(R.id.given_name")를 호출하여 RelativeLayout을 찾습니다.
  3. 메서드 setBackgroundColor()를 호출하여 레이아웃을 클래식오브젝트로 사용합니다.

언급URL : https://stackoverflow.com/questions/12523005/how-set-background-drawable-programmatically-in-android

반응형