Android 에서 빠 르 고 편리 하 게 원 각 버튼 을 실현 하 는 방법 에 대한 상세 한 설명

5481 단어 android원 각 버튼
머리말
원 각 버튼 은 우리 가 인 터 페 이 스 를 만 들 때 자주 만 나 는 UI 스타일 이라는 것 을 잘 알 고 있 을 것 이다.일반적인 방법 은 drawable 을 만 드 는 것 입 니 다.예 를 들 어 다음 과 같 습 니 다.

<?xml version="1.0" encoding="UTF-8"?> 
<shape 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:shape="rectangle"> 
 <!--       --> 
 <solid android:color="#ffae00" /> 

 <!--       --> 
 <corners android:radius="10dp" /> 
</shape>
Layout 파일 에 Button 의 background 속성 에 이 drawable.xml 를 설정 하면 됩 니 다.
그러나 이렇게 하면 버튼 을 누 를 때마다 drawable 파일 을 새로 만들어 야 합 니 다.여러 drawable 이 많아 지면 어 지 럽 습 니 다.
color 와 radius 를 Button 의 속성 에 넣 을 수 있 습 니 다.그러면 매번 drawable.xml 을 끌 지 않 아 도 됩 니 다.그 렇 죠?
사용자 정의 RoundCornerButton

<widget.RoundCornerButton
 android:id="@+id/btn_commit"
 android:layout_width="100dp"
 android:layout_height="40dp"
 android:gravity="center"
 android:text="    "
 app:rcb_backgroundColor="@color/yellow"
 app:rcb_backgroundColorDisabled="@color/light_grey"
 app:rcb_cornerRadius="20dp"
 />
이렇게 Layout 파일 에 배경 색 과 원 각 반경 을 직접 설정 할 수 있다 면 편리 하지 않 겠 습 니까?drawable 보다 유연 하 지 는 않 지만 디자인 학생 들 이 내 놓 은 원 각 버튼 의 수요 에 충분히 대처 할 수 있 습 니 다.
저 희 는 자신 을 정의 하 는 stylable 속성 으로 시작 하 겠 습 니 다.

<declare-styleable name="RoundCornerButton">
 <attr name="rcb_backgroundColor" format="color" />
 <attr name="rcb_backgroundColorDisabled" format="color" />
 <attr name="rcb_cornerRadius" format="dimension" />
</declare-styleable>
Drawable 에서 자신의 Drawable 을 확장 하 는 것 은 간단 합 니 다.
4.567917.구조 방법 에서 color 와 radius 에 전달 되 고 실습 하 는 화필 을 만 듭 니 다4.567917.복 사 draw 방법 은 기 존의 원 각 사각형 을 그 리 는 방법 으로 호출 할 수 있다4.567917.setRect 방법 을 외부 에 노출 하여 그리 기 구역 의 너비 와 높이 를 설정 합 니 다.

class RoundCornerDrawable extends Drawable {

 final int color;
 final float radius;
 final Paint paint;
 final RectF rectF;

 RoundCornerDrawable(int color, float radius) {
  this.color = color;
  this.radius = radius;

  //      
  this.paint = new Paint();
  paint.setStyle(Paint.Style.FILL);
  paint.setAntiAlias(true);
  paint.setColor(color);

  this.rectF = new RectF();
 }

 //     Drawable  
 public void setRect(int width, int height) {
  this.rectF.left = 0;
  this.rectF.top = 0;
  this.rectF.right = width;
  this.rectF.bottom = height;
 }

 @Override
 public void draw(@NonNull Canvas canvas) {
  canvas.drawRoundRect(rectF, radius, radius, paint); //      ,     
 }

 //      
}
자신의 Button 류 를 정의 하 는 데 몇 가지 요점 이 있 습 니 다.
4.567917.일반적인 사용자 정의 View 와 마찬가지 로 세 가지 구조 방법 을 복사 합 니 다
  • AttributeSet 에서 사용자 정의 속성 backgroundColor 와 cornerRadius 를 읽 습 니 다.여 기 는 backgroundColorDisabled 를 잠시 무시 합 니 다
  • 모든 상태(예 를 들 어 일반,사용 하지 않 음,누 르 기)는 RoundCorner Drawable 로 StateListDrawable 로 조합 합 니 다
  • onLayout 를 사용 할 때 모든 RoundCorner Drawable 의 사 이 즈 를 바 꾸 는 것 을 기억 하 세 요
  • 
    public class RoundCornerButton extends AppCompatButton {
    
     private int colorNormal;
     private float cornerRadius;
     private RoundCornerDrawable bgDrawableNormal = null;
    
     //         
     //            initCornerBackground     
    
     private void initCornerBackground(AttributeSet attrs, int defStyleAttr) {
      TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RoundCornerButton, defStyleAttr, 0);
    
      this.cornerRadius = a.getDimension(R.styleable.RoundCornerButton_rcb_cornerRadius, 0);
      this.colorNormal = a.getColor(R.styleable.RoundCornerButton_rcb_backgroundColor, 0);
      makeBackgroundDrawable();
    
      a.recycle();
     }
    
     private void makeBackgroundDrawable() {
      bgDrawableNormal = new RoundCornerDrawable(this.colorNormal, this.cornerRadius);
      bgDrawableNormal.setRect(getWidth(), getHeight());
    
      //                      
      //        StateListDrawable
      StateListDrawable bgDrawable = new StateListDrawable();
      bgDrawable.addState(new int[]{android.R.attr.state_enabled, -android.R.attr.state_pressed}, bgDrawableNormal);
      //       ,       
      setBackgroundDrawable(bgDrawable);
     }
    
     @Override
     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
      super.onLayout(changed, left, top, right, bottom);
    
      // layout     draw,       drawable   
      if (bgDrawableNormal != null) {
       bgDrawableNormal.setRect(right - left, bottom - top);
      }
      //       ,       
     }
    }
    데모 소스 코드 첨부:https://github.com/realxu/CodeSamples/tree/master/Android/RoundCornerButtonDemo
    이 정도 면 됩 니 다.효과 좀 봅 시다.

    총결산
    이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.

    좋은 웹페이지 즐겨찾기