Почему время инфляции для пользовательского представления в Android с использованием Java XML такое долгое?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Почему время инфляции для пользовательского представления в Android с использованием Java XML такое долгое?

Сообщение Anonymous »

проблема
Время, необходимое для накачивания, составляет около 15–8 мс для пользовательского представления, что очень долго.

Код: Выделить всё

        long startTime = System.nanoTime();
LayoutInflater.from(context).inflate(R.layout.view_profile, this, true);
binding = ViewProfileBinding.bind(this);
long durationNanos = System.nanoTime() - startTime;
Макет очень прост ConstraintLayout с TextView. (будь то ConstraintLayout или LinearLayout, медлительность одинакова).
Это просто очень простой проект hello world, созданный с помощью ИИ для простого тестирования производительности.
Что не так?
код

Код: Выделить всё

package com.example.myapp;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.example.myapp.databinding.ViewProfileBinding;  // Generated class

public class ProfileView extends ConstraintLayout {

private static final String TAG = "ProfileViewPerformance";

// The binding object for our layout
private ViewProfileBinding binding;

public ProfileView(@NonNull Context context) {
super(context);
init(context, null);
}

public ProfileView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}

public ProfileView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}

private void init(Context context, AttributeSet attrs) {
// --- PERFORMANCE MEASUREMENT START ---
long startTime = System.nanoTime();

// Inflate the layout and attach it to this view (the 'true' parameter)
LayoutInflater.from(context).inflate(R.layout.view_profile, this, true);

// Use View Binding to get references to the child views
binding = ViewProfileBinding.bind(this);

// --- PERFORMANCE MEASUREMENT END ---
long durationNanos = System.nanoTime() - startTime;
Log.d(TAG, String.format("Inflation time: %,d ns (%.3f ms)",
durationNanos,
durationNanos / 1_000_000.0));

// If attributes were passed from XML, process them
if (attrs != null) {
TypedArray typedArray = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ProfileView,
0, 0);
try {
String name = typedArray.getString(R.styleable.ProfileView_profileName);
String email = typedArray.getString(R.styleable.ProfileView_profileEmail);
Drawable avatar = typedArray.getDrawable(R.styleable.ProfileView_profileAvatar);

if (name != null) {
setProfileName(name);
}
if (email != null) {
setProfileEmail(email);
}
if (avatar != null) {
setProfileAvatar(avatar);
}
} finally {
// IMPORTANT: Always recycle the TypedArray.
typedArray.recycle();
}
}
}

// --- Public API Methods ---

public void setProfileName(String name) {
binding.profileNameText.setText(name);
}

public void setProfileEmail(String email) {
binding.profileEmailText.setText(email);
}

public void setProfileAvatar(Drawable drawable) {
binding.profileAvatarImage.setImageDrawable(drawable);
}

public void setProfileAvatar(int drawableResId) {
binding.profileAvatarImage.setImageResource(drawableResId);
}
}

комментарий
Эта медлительность не имеет для меня никакого смысла. Я что-то пропустил в мире Android? (Все онлайн-ресурсы Android очень ограничены, даже для такой распространенной проблемы? Объяснения искусственного интеллекта также ужасны из-за отсутствия ресурсов для обучения.)
Если у меня есть 3 пользовательских представления, отставание будет очевидным.
Я не могу перейти на Jetpack Compose или Kotlin. (Это проект, в котором используется множество Java JNI SDK.)

Подробнее здесь: https://stackoverflow.com/questions/798 ... g-java-xml
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»