0

I'm trying to make my own XML element. For learning purposes, I just tried printing out some parameters into the Log, but the program won't start. Android Studio tells me that there is no suitable constructor found, neither in my class, nor in the LinearLayout class.

I tried using this example: 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>

and the class:

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();
    }
}
Community
  • 1
  • 1
lennyy
  • 476
  • 6
  • 31

1 Answers1

1

all the View's subclass constructors take a Context object as parameter.

public AccordionWidget(AttributeSet attrs) {

should be

public AccordionWidget(Context context, AttributeSet attrs) {
   super(context, attrs);
AndiGeeky
  • 10,644
  • 6
  • 46
  • 64
Blackbelt
  • 148,780
  • 26
  • 271
  • 285