没有合适的构造函数 - 学习android

时间:2016-03-21 10:37:49

标签: android xml constructor

我试图制作自己的XML元素。出于学习目的,我只是尝试将一些参数打印到日志中,但程序不会启动。 Android Studio告诉我,在我的类和LinearLayout类中都找不到合适的构造函数。

我尝试使用此示例:Declaring a custom android UI element using XML

attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="accordion">
        <attr name="text" format="string"/>
        <attr name="text_color" format="color"/>
        <attr name="backgroundColorPressed" format="color"/>
        <attr name="backgroundColorUnpressed" format="color"/>
    </declare-styleable>
</resources>

main.xml中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:accordion="http://schemas.android.com/apk/res-auto"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFFFF"
    android:orientation="vertical">

    <mika.actual.AccordionWidget
        accordion:text="Swag"
        accordion:text_color="@color/text_color"
        accordion:backgroundColorPressed="@color/button_pressed"
        accordion:backgroundColorUnpressed="@color/button_not_pressed" />

    <!-- Some other stuff that should not affect this -->

</LinearLayout>

和班级:

package mika.actual;

import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

public class AccordionWidget extends LinearLayout{

    public AccordionWidget(AttributeSet attrs) {

        TypedArray a = getContext().obtainStyledAttributes(
                attrs,
                R.styleable.accordion);

        //Use a
        Log.i("test", a.getString(
                R.styleable.accordion_text));
        Log.i("test", "" + a.getColor(
                R.styleable.accordion_backgroundColorPressed, Color.BLACK));
        Log.i("test", "" + a.getColor(
                R.styleable.accordion_backgroundColorUnpressed, Color.BLACK));
        Log.i("test", "" + a.getColor(
                R.styleable.accordion_text_color, Color.BLACK));

        //Don't forget this
        a.recycle();
    }
}

1 个答案:

答案 0 :(得分:1)

所有View的子类构造函数都将Context对象作为参数。

public AccordionWidget(AttributeSet attrs) {

应该是

public AccordionWidget(Context context, AttributeSet attrs) {
   super(context, attrs);