developer tip

프로그래밍 방식으로 모서리를 둥글게하고 임의의 배경색을 설정하는 방법

optionbox 2020. 8. 14. 07:40
반응형

프로그래밍 방식으로 모서리를 둥글게하고 임의의 배경색을 설정하는 방법


뷰의 모서리를 둥글게하고 런타임에 내용에 따라 뷰의 색상을 변경하고 싶습니다.

TextView v = new TextView(context);
v.setText(tagsList.get(i));
if(i%2 == 0){
    v.setBackgroundColor(Color.RED);
}else{
    v.setBackgroundColor(Color.BLUE);
}

v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
v.setPadding(twoDP, twoDP, twoDP, twoDP);               
v.setBackgroundResource(R.drawable.tags_rounded_corners);

드로어 블과 색상이 겹 치길 바랐지만 그렇지 않습니다. 내가 두 번째로 실행하는 것이 결과 배경입니다.

런타임까지 배경색이 결정되지 않는다는 점을 염두에두고이 뷰를 프로그래밍 방식으로 만드는 방법이 있습니까?

편집 : 테스트를 위해 지금은 빨간색과 파란색으로 만 바꿉니다. 나중에 사용자가 색상을 선택할 수 있습니다.

편집하다:

tags_rounded_corners.xml :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners 
         android:bottomRightRadius="2dp" 
         android:bottomLeftRadius="2dp" 
         android:topLeftRadius="2dp" 
         android:topRightRadius="2dp"/>
</shape>

대신 setBackgroundColor배경 드로어 블을 검색하고 색상을 설정합니다.

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

또한 내 패딩을 정의 할 수 있습니다 tags_rounded_corners.xml.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <padding
    android:top="2dp"
    android:left="2dp"
    android:bottom="2dp"
    android:right="2dp" />
</shape> 

둥근 모서리를 설정하고 임의의 배경색을 뷰에 추가하는 완전한 프로그래밍 방식입니다. 나는 코드를 테스트하지 않았지만 당신은 아이디어를 얻었습니다.

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( R.id.my_view );
 view.setBackground(shape);

여기서는 그라디언트 드로어 블을 사용하여 이러한 방법을 제공하지 GradientDrawable#setCornerRadius않기 때문에 사용할 수 있습니다 ShapeDrawable.


이를 수행하는 가장 빠른 방법은 다음과 같습니다.

GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction 
            new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius

//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
     view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);    

다음 과 같이 DrawableCompat 를 사용하면 더 잘 얻을 수 있습니다 .

Drawable backgroundDrawable = view.getBackground();             
DrawableCompat.setTint(backgroundDrawable, newColor);

뇌졸중이없는 경우 다음을 사용할 수 있습니다.

colorDrawable = resources.getDrawable(R.drawable.x_sd_circle); 

colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

하지만 이것은 또한 획 색상을 변경합니다


모든 항목 (레이아웃, 텍스트보기)의 색상을 동적으로 변경할 수 있습니다. 레이아웃에서 프로그래밍 방식으로 색상을 설정하려면 아래 코드를 시도하십시오.

activity.java 파일에서


String quote_bg_color = "#FFC107"
quoteContainer= (LinearLayout)view.findViewById(R.id.id_quotecontainer);
quoteContainer.setBackgroundResource(R.drawable.layout_round);
GradientDrawable drawable = (GradientDrawable) quoteContainer.getBackground();
drawable.setColor(Color.parseColor(quote_bg_color));

드로어 블 폴더에 layout_round.xml 생성

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimaryLight"/>
    <stroke android:width="0dp" android:color="#B1BCBE" />
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>

activity.xml 파일의 레이아웃

<LinearLayout
        android:id="@+id/id_quotecontainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

----other components---

</LinearLayout>



다음은 확장을 사용하는 예입니다. 이것은 뷰의 너비와 높이가 같다고 가정합니다.

Need to use a layout change listener to get the view size. Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)

fun View.setRoundedBackground(@ColorInt color: Int) {
    addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
        override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {

            val shape = GradientDrawable()
            shape.cornerRadius = measuredHeight / 2f
            shape.setColor(color)

            background = shape

            removeOnLayoutChangeListener(this)
        }
    })
}

참고URL : https://stackoverflow.com/questions/18391830/how-to-programmatically-round-corners-and-set-random-background-colors

반응형