Связывание XML с представлением компонентов - PullRequest
0 голосов
/ 27 апреля 2018

В настоящее время я борюсь с тем, что, по моему мнению, должно быть довольно простым. Я создал LinearLayout в XML-файле, который я хочу связать с CustomComponent, который расширяет LinearLayout, что означает, что я начал задом наперед.

Обычно я сначала создаю CustomComponent, и это создает XML-файл, связанный тегом, <my.package.CustomComponent> (Если я не ошибаюсь, это единственный способ, которым они связаны (?)), И я делаю вещи в onDraw(). Но в этом проекте я делаю макет через XML, а не onDraw().

Связывание XML с активностью выполняется setContentView(R.layout.customView), но я не могу сделать это в CustomComponent, поскольку у меня нет унаследованного onCreate() метода.

sidenote: В XML все мои кнопки с изображениями имеют android:onClick=chooseButton, но по понятной причине не может найти этот метод ...

Есть идеи относительно этой проблемы?

EDIT : кажется, что эти два файла не связаны между собой, потому что в xml android:onClick="chooseButton" среда IDE говорит: «не удается разрешить символ ChooseButton»

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/dial_view_id"
    android:layout_width="match_parent"
    tools:context=".DialView"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <com.package.CustomView
        android:id="@+id/drawingview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1">


        <ImageButton
            android:id="@+id/button1"
            android:onClick="chooseButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:scaleType="fitCenter"
            android:background="@drawable/ic_dialpad_1_blue" />

        <ImageButton
            android:id="@+id/button2"
            android:onClick="chooseButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/ic_dialpad_2_blue" 
                 ------code repeated below-----/>

CustomView:

public class CustomView extends LinearLayout {
    private String mExampleString;
    private int mExampleColor = Color.RED;
    private float mExampleDimension = 0;
    private Drawable mExampleDrawable;
    private TextPaint mTextPaint;
    private float mTextWidth;
    private float mTextHeight;
    private ImageButton button_0, button_1, button_2, button_3, button_4, button_5, button_6;
    private ImageButton button_7, button_8, button_9, button_star, button_pound;
    private boolean clicked = false;
    private SparseIntArray drawables = new SparseIntArray();

    public DialView(Context context) {
        super(context);

    }

    public DialView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public DialView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.DialView, defStyle, 0);

        mExampleString = a.getString(
                R.styleable.DialView_exampleString);
        mExampleColor = a.getColor(
                R.styleable.DialView_exampleColor,
                mExampleColor);
        // Use getDimensionPixelSize or getDimensionPixelOffset when dealing with
        // values that should fall on pixel boundaries.
        mExampleDimension = a.getDimension(
                R.styleable.DialView_exampleDimension,
                mExampleDimension);

        if (a.hasValue(R.styleable.DialView_exampleDrawable)) {
            mExampleDrawable = a.getDrawable(
                    R.styleable.DialView_exampleDrawable);
            mExampleDrawable.setCallback(this);
        }

        a.recycle();

        // Set up a default TextPaint object
        mTextPaint = new TextPaint();
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextAlign(Paint.Align.LEFT);

        // Update TextPaint and text measurements from attributes
        invalidateTextPaintAndMeasurements();
    }

    private void invalidateTextPaintAndMeasurements() {
        mTextPaint.setTextSize(mExampleDimension);
        mTextPaint.setColor(mExampleColor);
        mTextWidth = mTextPaint.measureText(mExampleString);

        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        mTextHeight = fontMetrics.bottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    public void getButtons(){}

    public void chooseButton(View v){}

    public void switchBackground(ImageButton button){}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...