2016-03-21 77 views
0

我想让自己的XML元素。出于学习目的,我只是试着在日志中输出一些参数,但程序不会启动。 Android Studio告诉我没有找到合适的构造函数,无论是在我的类还是在LinearLayout类中。没有合适的构造函数 - 学习android

我尝试使用这个例子: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

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

public AccordionWidget(AttributeSet attrs) { 

应该

public AccordionWidget(Context context, AttributeSet attrs) { 
    super(context, attrs); 
相关问题