Sobes.tech
Middle

Jak propojit vlastní pohled s vlastním rozložením?

sobes.tech AI

Odpověď od AI

Existuje několik způsobů:

  1. Použití konstruktoru s atributovým souborem AttributeSet: To je nejběžnější způsob. V konstruktoru View lze načíst atributy z XML a použít je.

    public class MyCustomView extends View {
    
        public MyCustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            // Čtení atributů z attrs
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
            // Získání hodnot atributů, například:
            // int someValue = a.getInt(R.styleable.MyCustomView_someAttribute, defaultValue);
            a.recycle(); // Je důležité uvolnit TypedArray
    
            // Inicializace View na základě načtených atributů
            // ...
        }
    
        // ... další konstruktory a metody
    }
    

    Při definování vlastního layoutu v XML lze použít tyto atributy:

    <com.example.app.MyCustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:someAttribute="someValue" />
    
  2. Inflace layoutu uvnitř View: Pokud View sestává z několika dalších View, lze je inflatovat z samostatného XML souboru uvnitř vlastního View.

    public class MyCompositeView extends LinearLayout {
    
        public MyCompositeView(Context context, AttributeSet attrs) {
            super(context, attrs);
            LayoutInflater.from(context).inflate(R.layout.my_custom_layout, this, true);
            // Nyní lze najít prvky uvnitř my_custom_layout
            // TextView myTextView = findViewById(R.id.myTextView);
            // ...
        }
    
        // ... další konstruktory a metody
    }
    

    my_custom_layout.xml může vypadat takto:

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/myTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Hello Custom Layout!" />
    
        <!-- další prvky rozvržení -->
    
    </LinearLayout>
    

    Tento vlastní layout MyCompositeView lze poté použít v jiném XML souboru:

    <com.example.app.MyCompositeView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    

Volba metody závisí na složitosti vlastního View: pro jednoduché View s minimem prvků postačuje první způsob, pro složitější View s vnitřní strukturou je vhodnější druhý.