2016-03-21 14 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); 
する必要があります
関連する問題