1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.android.setupdesign.view; 18 19 import android.annotation.TargetApi; 20 import android.content.Context; 21 import android.os.Build.VERSION_CODES; 22 import androidx.annotation.Nullable; 23 import android.util.AttributeSet; 24 import android.widget.Checkable; 25 import android.widget.LinearLayout; 26 27 /** 28 * A LinearLayout which is checkable. This will set the checked state when {@link 29 * #onCreateDrawableState(int)} is called, and can be used with {@code android:duplicateParentState} 30 * to propagate the drawable state to child views. 31 */ 32 public class CheckableLinearLayout extends LinearLayout implements Checkable { 33 34 private boolean checked = false; 35 CheckableLinearLayout(Context context)36 public CheckableLinearLayout(Context context) { 37 super(context); 38 } 39 CheckableLinearLayout(Context context, @Nullable AttributeSet attrs)40 public CheckableLinearLayout(Context context, @Nullable AttributeSet attrs) { 41 super(context, attrs); 42 } 43 44 @TargetApi(VERSION_CODES.HONEYCOMB) CheckableLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr)45 public CheckableLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 46 super(context, attrs, defStyleAttr); 47 } 48 49 @TargetApi(VERSION_CODES.LOLLIPOP) CheckableLinearLayout( Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)50 public CheckableLinearLayout( 51 Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 52 super(context, attrs, defStyleAttr, defStyleRes); 53 } 54 55 { 56 setFocusable(true); 57 } 58 59 @Override onCreateDrawableState(int extraSpace)60 protected int[] onCreateDrawableState(int extraSpace) { 61 if (this.checked) { 62 final int[] superStates = super.onCreateDrawableState(extraSpace + 1); 63 final int[] checked = new int[] {android.R.attr.state_checked}; 64 return mergeDrawableStates(superStates, checked); 65 } else { 66 return super.onCreateDrawableState(extraSpace); 67 } 68 } 69 70 @Override setChecked(boolean checked)71 public void setChecked(boolean checked) { 72 this.checked = checked; 73 refreshDrawableState(); 74 } 75 76 @Override isChecked()77 public boolean isChecked() { 78 return checked; 79 } 80 81 @Override toggle()82 public void toggle() { 83 setChecked(!isChecked()); 84 } 85 } 86