to top
CustomChoiceList / src / com.example.android.customchoicelist /

CheckableLinearLayout.java

1
/*
2
 * Copyright 2013 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.example.android.customchoicelist;
18
 
19
import android.content.Context;
20
import android.util.AttributeSet;
21
import android.util.Log;
22
import android.view.View;
23
import android.widget.Checkable;
24
import android.widget.LinearLayout;
25
 
26
/**
27
 * This is a simple wrapper for {@link android.widget.LinearLayout} that implements the {@link android.widget.Checkable}
28
 * interface by keeping an internal 'checked' state flag.
29
 * <p>
30
 * This can be used as the root view for a custom list item layout for
31
 * {@link android.widget.AbsListView} elements with a
32
 * {@link android.widget.AbsListView#setChoiceMode(int) choiceMode} set.
33
 */
34
public class CheckableLinearLayout extends LinearLayout implements Checkable {
35
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
36
 
37
    private boolean mChecked = false;
38
 
39
    public CheckableLinearLayout(Context context, AttributeSet attrs) {
40
        super(context, attrs);
41
    }
42
 
43
    public boolean isChecked() {
44
        return mChecked;
45
    }
46
 
47
    public void setChecked(boolean b) {
48
        if (b != mChecked) {
49
            mChecked = b;
50
            refreshDrawableState();
51
        }
52
    }
53
 
54
    public void toggle() {
55
        setChecked(!mChecked);
56
    }
57
 
58
    @Override
59
    public int[] onCreateDrawableState(int extraSpace) {
60
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
61
        if (isChecked()) {
62
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
63
        }
64
        return drawableState;
65
    }
66
}