Android: автоматически создавать переменные для всех идентификаторов в xml

Я заметил, что одной из самых утомительных частей разработки Android является дизайн макета, даже с компоновщиком.

после настройки графики, затем макет, создание переменных ассоциаций с элементами макета очень утомительно, например ImageButton myButton = (ImageButton)findViewById(R.id.myButton);

в больших макетах они могут быть утомительными, чтобы отслеживать (вспоминая имена элементов), а затем необходимость добавлять больше переменных в любом порядке становится разочаровывающей.

немного смягчить это, было бы очень удобно, если бы все идентификаторы, которые я объявил в XML, были автоматически связаны с их соответствующими переменными, и все эти типы данных уже были включены в этот класс

есть что-то, что уже делает это?

например, если я пишу

 <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/myButton" android:id="@+id/myButton"></ImageButton>

затем я хотел бы, чтобы классы, которые включают этот макет уже есть

 import android.ImageButton;

 ImageButton myButton;

 myButton = (ImageButton)findViewById(R.id.myButton);

это настройка или функция для запроса? Я использую Eclipse IDE и это было бы очень удобно

4 ответов


попробуйте использовать Android Аннотации. Он предоставляет полезные аннотации для замены кода шаблона.

, например,@ViewById документация: просто объявите поля аннотированными

@ViewById
EditText myEditText;

@ViewById(R.id.myTextView)
TextView textView;

заменяет

EditText myEditText;

TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    myEditText = (EditText) findViewById(R.id.myEditText);
    textView = (TextView) findViewById(R.id.myTextView);
}

Я сделал инструмент для автоматического создания кода Java для связывания макета XML и логики программы вместе.

в основном он принимает XML-макет и генерирует весь необходимый Java-код для вас в одно мгновение. Существует поддержка базовых переменных-членов, шаблонов ViewHolder, ArrayAdapter, CursorAdapter и типов кода RoboGuice.

вы можете найти его здесь: Android Layout Finder / Жужжание Android


это запрос функции. Это очень хорошо, и я думаю, что это было бы очень полезно; с другой стороны, есть случаи, когда это не будет работать очень хорошо, например, если вы раздуваете представления динамически и не знаете, во время компиляции, какой вид конкретного действия будет раздуваться. Однако я склонен думать, что этот случай будет исключением, а не правилом.

самый простой способ сделать это - закодировать скрипт, который сканирует ваши XML-файлы макета в поисках компоненты с ID и создает .Java файлы с соответствующими определениями. Затем ваши действия могут быть получены из этих автоматически сгенерированных классов. Что-то вроде этого:--2-->

при обработке скриптом создается класс:

class FooBarLayoutActivityBase extends Activity ... {
  protected ImageButton myButton;

  FooBarLayoutActivityBase() {
    myButton = (ImageButton)findViewById(R.id.myButton);
  }
}

затем, вы можете просто наследовать от этого базового класса, чтобы использовать компоненты...

подход скрипта прост и не требует от вас углубляться в код toolchain , но вы также можете это сделать непосредственно в плагин ADT.


обновление : Android View Binding (AVB) генератор кода, это именно то, что я собираюсь сказать :|


регулярное выражение!

у меня была такая же проблема, и я попытался решить ее сам, поэтому я превратился в REGEX внутри поиска и замены дорогой Android Studio. Лично я использую ButterKnife для инъекции зависимостей с аннотацией java, но более важной частью является автоматизация процедура превращения идентификаторов в XML-макете в объекты java. Его вид, как Android Layout Finder / Жужжание Android (веб-сайт имеет больше функций, но старый: () ответ, но с результатом аннотации.

  1. перейти к вашей xml и выберите все идентификаторы с этим регулярным выражением (\+id/.* ). Для этого сначала нажмите Ctrl + F чтобы открыть панель поиска, убедитесь, что есть. затем введите регулярное выражение ( \+id/.* ) внутри коробки а затем нажмите Ctrl + Alt + Shift + J для выбора всех вхождений. Теперь Ctrl + C чтобы скопировать их (вы знаете ярлык).

например, у меня был этот макет:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutDirection="rtl"
    tools:context=".jobs.return_from_entrance.ReturnFromEntranceActivity"
    tools:ignore="HardcodedText">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <GridLayout
            android:id="@+id/return_entrance_grid_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:columnCount="2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="شماره برگشت" />

            <TextView
                android:id="@+id/return_entrance_return_entrance_number_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="123123123"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="@string/owner_of_cargo" />

            <TextView
                android:id="@+id/return_entrance_owner_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="الجی"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="تاریخ و زمان" />

            <TextView
                android:id="@+id/return_entrance_time_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="12/12/12/ 12:12"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="نوع حواله" />

            <TextView
                android:id="@+id/return_entrance_kind_of_order_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="حواله"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="خریدار" />


            <TextView
                android:id="@+id/return_entrance_buyer_name_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="علی امیدی"
                android:textColor="@android:color/black"
                android:textSize="18sp" />


            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="مقصد" />

            <TextView
                android:id="@+id/return_entrance_destination_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="آزادی"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="وزن ناخالص" />

            <TextView
                android:id="@+id/return_entrance_gross_weight_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="123"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="شماره جواز" />

            <TextView
                android:id="@+id/return_entrance_permission_number_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="126545643"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="شماره بارنامه" />

            <TextView
                android:id="@+id/return_entrance_waybill_number_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="654"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="زمان ورود" />

            <TextView
                android:id="@+id/return_entrance_enter_time_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="21/12/12 22:22"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="زمان خروج" />

            <TextView
                android:id="@+id/return_entrance_exit_time_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="21/12/12 22:22"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="محوطه بارگیری" />

            <TextView
                android:id="@+id/return_entrance_load_location_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="حیاط"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="نیاز به جرثقیل" />

            <TextView
                android:id="@+id/return_entrance_is_crane_needed_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="ندارد"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="نیاز به لیفتراک" />

            <TextView
                android:id="@+id/return_entrance_is_forklift_needed_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="ندارد"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <CheckBox
                android:id="@+id/return_entrance_internal_return_entrance_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="@dimen/margin_large"
                android:layout_marginStart="@dimen/margin_medium"
                android:layout_marginTop="@dimen/margin_large"
                android:text="خروج داخلی" />

            <View
                android:layout_width="0dp"
                android:layout_height="0dp" />

            <CheckBox
                android:id="@+id/return_entrance_warehouse_delivery_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="@dimen/margin_large"
                android:layout_marginStart="@dimen/margin_medium"
                android:layout_marginTop="@dimen/margin_large"
                android:text="تحویل در انبار" />

            <View
                android:layout_width="0dp"
                android:layout_height="0dp" />

            <Button
                android:id="@+id/return_entrance_location_delivery_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin_large"
                android:text="تحویل در محل" />

            <View
                android:layout_width="0dp"
                android:layout_height="0dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="عکس راننده" />

            <ImageView
                android:id="@+id/return_entrance_driver_image_view"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:layout_gravity="center"
                android:layout_marginTop="@dimen/item_margin"
                android:src="@drawable/ic_account_circle_black_24dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="@string/name_of_driver" />

            <TextView
                android:id="@+id/return_entrance_name_of_driver_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="علی امیدی"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="@string/kind_of_car" />

            <TextView
                android:id="@+id/return_entrance_kind_of_car_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="وانت مزدا"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="@string/plaque" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin_large"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/return_entrance_plaque_2digit_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/plaque_background"
                    android:padding="10dp"
                    android:text="11"
                    android:textColor="@android:color/black"
                    android:textSize="10pt"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/return_entrance_plaque_6digit_text_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/plaque_background"
                    android:padding="10dp"
                    android:text="999ج77"
                    android:textColor="@android:color/black"
                    android:textSize="10pt"
                    android:textStyle="bold" />
            </LinearLayout>
        </GridLayout>

        <Button
            android:id="@+id/return_entrance_barcode_scan_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="@dimen/margin_small"
            android:drawableStart="@drawable/ic_barcode"
            android:padding="@dimen/margin_medium"
            android:text="@string/scan_barcode"
            android:textSize="18sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/return_entrance_grid_layout" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/return_entrance_cargo_list_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/return_entrance_barcode_scan_button" />

        <GridLayout
            android:id="@+id/return_entrance_bottom_grid_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:columnCount="2"
            android:layoutDirection="rtl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/return_entrance_cargo_list_recycler_view">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="میزان موجودی کالای قابل تحویل" />

            <TextView
                android:id="@+id/return_entrance_deliverable_availability_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/text_margin"
                android:text="50"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

        </GridLayout>

        <LinearLayout
            android:id="@+id/return_entrance_bottom_linear_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/return_entrance_bottom_grid_layout">

            <Button
                android:id="@+id/return_entrance_cost_report_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin_medium"
                android:text="گزارش هزینه" />

            <Button
                android:id="@+id/return_entrance_confirm_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/margin_medium"
                android:text="تایید برگشت" />

        </LinearLayout>

    </android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>

много текстовых представлений для заполнения, да?

  1. перейти к вашей java class и вставьте скопированные идентификаторы (Ctrl + V). таким образом, у нас есть куча идентификаторов, которые мы хотим изменить их на объекты java. в нашем примере мои идентификаторы будут такими :

    +id/return_entrance_grid_layout"
    +id/return_entrance_return_entrance_number_text_view"
    +id/return_entrance_owner_text_view"
    +id/return_entrance_time_text_view"
    ...
    

его время, чтобы найти и заменить! Итак, сначала мы ударили Ctrl + R чтобы открыть панель поиска и замены. (убедитесь, что это ) теперь я собираюсь сделать некоторые найти и заменить, чтобы получить идеальный результат:

  1. найти : \+id/(.*)" заменить на: @BindView(R.id.) Итак, мы будем иметь это:

    @BindView(R.id.return_entrance_grid_layout)
    @BindView(R.id.return_entrance_return_entrance_number_text_view)
    @BindView(R.id.return_entrance_owner_text_view)
    @BindView(R.id.return_entrance_time_text_view)
    ...
    

теперь пришло время определить каждый тип переменной и назвать их. моей XML именования WHERE_DESCRIPTION_WHAT узор, ( что-то вроде этого ). поэтому для имени переменной я хочу удалить WHERE часть. а затем определите объект тип. Итак, мы идем:

  1. найти: (@BindView\(R\.id\.return_entrance_(.*)_text_view\)) Заменить на: TextView TextView; результатом будет:

    @BindView(R.id.return_entrance_grid_layout)
    @BindView(R.id.return_entrance_return_entrance_number_text_view) TextView return_entrance_numberTextView;
    @BindView(R.id.return_entrance_owner_text_view) TextView ownerTextView;
    @BindView(R.id.return_entrance_time_text_view) TextView timeTextView;
    @BindView(R.id.return_entrance_kind_of_order_text_view) TextView kind_of_orderTextView;
    ...
    

(просто нажмите Ctrl + Alt + L переформатировать код) имена ulgy :( . поэтому мы делаем это с camelCase! :

  1. найти: TextView \b(.*)_(.*) Заменить На: TextView \u и результат будет:

    @BindView(R.id.return_entrance_owner_text_view)
    TextView ownerTextView;
    @BindView(R.id.return_entrance_time_text_view)
    TextView timeTextView;
    @BindView(R.id.return_entrance_kind_of_order_text_view)
    TextView kind_ofOrderTextView;
    @BindView(R.id.return_entrance_buyer_name_text_view)
    TextView buyerNameTextView;
    @BindView(R.id.return_entrance_destination_text_view)
    TextView destinationTextView;
    

если вы повторите последнюю часть, любое имя, которое имеет более одного подчеркивания, каждый _ будет заменен на верхний регистр следующего символа. Итак, в этом примере, если я найду:TextView \b(.*)_(.*) Заменить На: TextView \u опять же, мой TextView kind_ofOrderTextView; будет TextView kindOfOrderTextView;

это может показаться немного сложным, но когда вы привыкнете к нему, он становится таким быстро, и это становится настолько более полезно! например, представьте в MVP, у Model С таким же String имена TextViews, поэтому вы можете сделать это, чтобы установить все свои тексты " из Model с аналогичным подходом...