【问题标题】:Fragment is too slow when change on bottomnavigatioview?在底部导航视图上更改时片段太慢?
【发布时间】:2020-11-13 22:43:03
【问题描述】:

我的片段在更新布局中花费了很多时间这是因为片段中有很多代码如何解决这个问题请帮助我

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

<data>

</data>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/lyttabs"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:gravity="center"
            android:layout_marginTop="20dp"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">


            <com.bugfree.caviar.fonts.BabesNeueProBold
                android:textStyle="bold"
                android:layout_weight="1"
                android:textColor="@color/black_text"
                android:textSize="30dp"
                android:layout_width="0dp"
                android:text="My Events That I am..."
                android:layout_height="wrap_content" />

            <ImageView
                android:id="@+id/btn_plus"
                android:src="@drawable/plus"
                android:layout_width="20dp"
                android:layout_height="20dp" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.google.android.material.tabs.TabLayout

                app:tabIndicatorColor="@color/button_red_back"
                android:id="@+id/tabs"
                android:layout_marginTop="15dp"
                app:tabBackground="@drawable/tab_indicator_color"
                app:tabTextAppearance="@style/MyCustomTextAppearance"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabMode="fixed" />

            <androidx.viewpager.widget.ViewPager
                android:layout_marginTop="30dp"
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_behavior="@string/appbar_scrolling_view_behavior" />


        </LinearLayout>

    </LinearLayout>

    <LinearLayout android:id="@+id/lytCreateEvent"
        android:visibility="gone"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".activity.CreateEvent">



            <ImageView
                android:layout_marginEnd="15dp"
                android:layout_marginStart="15dp"
                android:layout_marginTop="30dp"
                android:id="@+id/imgBack"
                android:src="@drawable/back_black"
                android:layout_width="20dp"
                android:layout_height="20dp" />



        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">


            <LinearLayout
                android:layout_marginEnd="15dp"
                android:layout_marginStart="15dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp">

                    <com.bugfree.caviar.fonts.BabesNeueProBold
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Create event"
                        android:textColor="@color/black"
                        android:textSize="30dp" />

                </LinearLayout>

                <LinearLayout

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:orientation="vertical">

                    <com.bugfree.caviar.fonts.BabesNeueProBoldRegular
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Event title" />

                    <EditText
                        android:singleLine="true"
                        android:paddingStart="15dp"
                        android:layout_marginTop="10dp"
                        android:textColorHint="@color/black"
                        android:background="@drawable/edit_back"
                        android:id="@+id/edtEventTitle"
                        android:textSize="18dp"
                        android:layout_gravity="center"
                        android:hint="Beach Yoga!"
                        android:layout_width="match_parent"
                        android:layout_height="50dp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_marginTop="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"

                    android:orientation="vertical">


                    <com.bugfree.caviar.fonts.BabesNeueProBoldRegular
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Event type" />


                </LinearLayout>

                <RelativeLayout
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:background="@drawable/edit_back"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    android:orientation="horizontal">


                    <com.bugfree.caviar.fonts.BabesNeueProBoldRegular
                        android:layout_centerVertical="true"
                        android:paddingStart="15dp"
                        android:layout_width="wrap_content"
                        android:textColor="@color/black"
                        android:layout_height="wrap_content"
                        android:text="Business"
                        android:textSize="18dp" />

                    <ImageView
                        android:layout_centerVertical="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginEnd="15dp"
                        android:layout_width="12dp"
                        android:layout_height="12dp"
                        android:layout_alignParentEnd="true"
                        android:src="@drawable/down_arrow" />


                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:orientation="horizontal">


                    <com.bugfree.caviar.fonts.BabesNeueProBoldRegular
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Event description" />

                    <com.bugfree.caviar.fonts.BabesNeueProBoldRegular
                        android:layout_marginEnd="15dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:text="94/300" />

                </RelativeLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/custombutton_border_edittext"
                    android:orientation="vertical">

                    <EditText
                        android:textSize="18dp"
                        android:id="@+id/edtDescription"
                        android:textColorHint="@color/black_text_new"
                        android:padding="10dp"
                        android:layout_gravity="start"
                        android:gravity="start"
                        android:hint="Beach yoga with Alissia is a lifestyle focused on health,
                         wellness, and self-care through the practice of"
                        android:layout_width="match_parent"
                        android:layout_height="150dp"
                        android:background="@android:color/transparent" />


                </LinearLayout>

                <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp">

                 
                        <ImageView
                            android:layout_marginEnd="10dp"
                            android:layout_centerVertical="true"
                            android:tint="@color/black"
                            android:layout_alignParentEnd="true"
                            android:src="@drawable/down_arrowsmall"
                            android:layout_width="10dp"
                            android:layout_height="10dp" />


                    </RelativeLayout>


                    <EditText
                        android:paddingLeft="10dp"
                        android:layout_gravity="start"
                        android:gravity="start"
                        android:id="@+id/edtSplReq"
                        android:layout_width="match_parent"
                        android:layout_marginTop="15dp"
                        android:layout_height="100dp"
                        android:singleLine="true"
                        android:padding="10dp"
                        android:background="@drawable/lay_without_border"
                        android:hint="Add a special request[optional]"
                        android:textColorHint="#848484"
                        android:textSize="18dp" />


                    <Button
                        android:outlineProvider="bounds"
                        android:stateListAnimator="@null"
                        style="?android:attr/borderlessButtonStyle"
                        android:layout_marginBottom="35dp"
                        android:id="@+id/btnSubmit"
                        android:layout_marginTop="30dp"
                        android:textSize="18dp"
                        android:textAllCaps="false"
                        android:text="Submit"
                        android:textColor="@color/space_white"
                        android:background="@drawable/custombutton"
                        android:layout_width="match_parent"
                        android:layout_height="35dp" />

                </LinearLayout>

            </ScrollView>

            <LinearLayout
                android:id="@+id/lytTab"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <com.google.android.material.tabs.TabLayout

                    app:tabBackground="@drawable/tab_indicator_color"
                    app:tabIndicatorColor="@color/button_red_back"
                    android:id="@+id/tabsLOc"
                    android:layout_marginTop="10dp"
                    app:tabTextAppearance="@style/MyCustomTextAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabGravity="fill"
                    app:tabMode="fixed" />

                <androidx.viewpager.widget.ViewPager

                    android:id="@+id/viewPagerLoc"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

这是我的片段

public class EventFragment extends Fragment {
private View view;
ViewPagerAdapter viewPagerAdapter;
LocationPagerAdapter locationPagerAdapter;
private String current = "";
private String ddmmyyyy = "MMDDYYYY";
private Calendar cal = Calendar.getInstance();
FragmentEventBinding binding;
private OnFragmentInteractionListener mListener;
public EventFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    binding = DataBindingUtil.inflate(
            inflater, R.layout.fragment_event, container, false);

    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Bebas Neue Pro Regular.otf");



    binding.lytTopImg.setOnClickListener(v -> {
       binding.lytLocDetails.setVisibility(View.VISIBLE);
        binding.lytPartLocNew.setVisibility(View.GONE);

    });


    binding.imgTopEvent.setImageBitmap(SetBrightness(BitmapFactory.decodeResource(getResources(), R.drawable.dummy),-70));

    binding.imgBackLocDetail.setOnClickListener(v -> {
        binding.lytLocDetails.setVisibility(View.GONE);
        binding.lytPartLocNew.setVisibility(View.VISIBLE);
       /* Intent intent = new Intent(PartnerLocationActivity.this, LoactionDetails.class);
        startActivity(intent);*/
    });
    binding.btnPlus.setOnClickListener(v -> {

        binding.lyttabs.setVisibility(View.GONE);
        binding.lytCreateEvent.setVisibility(View.VISIBLE);
    });
    binding.imgBack.setOnClickListener(v -> {
        mListener.changeFragment(2);

        binding.lyttabs.setVisibility(View.VISIBLE);
        binding.lytCreateEvent.setVisibility(View.GONE);

    });

    binding.buttonCreateEvent.setOnClickListener(v -> {

        binding.lyttabs.setVisibility(View.VISIBLE);
        binding.lytCreateEvent.setVisibility(View.GONE);

    });
    binding.imgBackPartnerLoc.setOnClickListener(v -> {


        binding.lytPartLocNew.setVisibility(View.GONE);
        binding.lytCreateEvent.setVisibility(View.VISIBLE);

       /* Intent intent = new Intent(getActivity(), CreateEvent.class);
        startActivity(intent);*/
    });
    binding.lytTopPartLoc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            binding.lytLocDetails.setVisibility(View.VISIBLE);
            binding.lytPartLocNew.setVisibility(View.GONE);
        }
    });
    binding.buttonCreateEvent.setTypeface(font);
    binding.edtEventTitle.setTypeface(font);
    binding.edtDescription.setTypeface(font);
    binding.edtNameLoc.setTypeface(font);
    binding.edtAddressLoc.setTypeface(font);
    binding.rdbOne.setTypeface(font);
    binding.rdbGroup.setTypeface(font);
    binding.buttonPartnerloc.setOnClickListener(v -> {
        binding.lytPartLocNew.setVisibility(View.VISIBLE);
        binding.lytCreateEvent.setVisibility(View.GONE);
       /* Intent intent = new Intent(CreateEvent.this, PartnerLocationActivity.class);
        startActivity(intent);*/
    });
    binding.buttonCreateEvent.setOnClickListener(v -> {
        binding.lyttabs.setVisibility(View.VISIBLE);
        binding.lytCreateEvent.setVisibility(View.GONE);
    });

    binding.edtDob.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (!s.toString().equals(current)) {
                String clean = s.toString().replaceAll("[^\\d.]|\\.", "");
                String cleanC = current.replaceAll("[^\\d.]|\\.", "");

                int cl = clean.length();
                int sel = cl;
                for (int i = 2; i <= cl && i < 6; i += 2) {
                    sel++;
                }

                if (clean.equals(cleanC)) sel--;

                if (clean.length() < 8) {
                    clean = clean + ddmmyyyy.substring(clean.length());
                } else {

                    int day = Integer.parseInt(clean.substring(0, 2));
                    int mon = Integer.parseInt(clean.substring(2, 4));
                    int year = Integer.parseInt(clean.substring(4, 8));

                    mon = mon < 1 ? 1 : mon > 12 ? 12 : mon;
                    cal.set(Calendar.MONTH, mon - 1);
                    year = (year < 1900) ? 1900 : (year > 2100) ? 2100 : year;
                    cal.set(Calendar.YEAR, year);

                    day = (day > cal.getActualMaximum(Calendar.DATE)) ? cal.getActualMaximum(Calendar.DATE) : day;
                    clean = String.format("%02d%02d%02d", day, mon, year);
                }

                clean = String.format("%s/%s/%s", clean.substring(0, 2),
                        clean.substring(2, 4),
                        clean.substring(4, 8));

                sel = sel < 0 ? 0 : sel;
                current = clean;
                binding.edtDob.setText(current);
                binding.edtDob.setSelection(sel < current.length() ? sel : current.length());

            }
        }


        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {


            }catch (Exception ignored){

            }
        }
    }).start();

    viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
    binding.viewPager.setAdapter(viewPagerAdapter);
    binding.tabs.setupWithViewPager( binding.viewPager);

    /*binding.imgBack.setOnClickListener(v -> {
        binding.lytLocDetails.setVisibility(View.GONE);
        binding.lytPartLocNew.setVisibility(View.VISIBLE);
    });*/
    locationPagerAdapter = new LocationPagerAdapter(getFragmentManager());
    binding.viewPagerLoc.setAdapter(locationPagerAdapter);
    binding.tabsLOc.setupWithViewPager(binding.viewPagerLoc);

    binding.edtSplReq.setTypeface(font);
    binding.edtEmail.setTypeface(font);
    binding.edtPhone.setTypeface(font);
    binding.edtLastName.setTypeface(font);
    binding.edtFirstname.setTypeface(font);
    binding.btnSubmit.setTypeface(font);
    binding.btnFindTable.setTypeface(font);
    binding.btnFindTable.setOnClickListener(v -> {

        binding.lytBtnFind.setVisibility(View.GONE);
        binding.lytTab.setVisibility(View.GONE);
        binding.lytBookTable.setVisibility(View.VISIBLE);

    });
    binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            binding.lyttabs.setVisibility(View.VISIBLE);
            binding.lytLocDetails.setVisibility(View.GONE);
            binding.lytPartLocNew.setVisibility(View.GONE);
            binding.lytCreateEvent.setVisibility(View.GONE);
            binding.lytBookTable.setVisibility(View.GONE);
            binding.lytBtnFind.setVisibility(View.VISIBLE);
            binding.lytTab.setVisibility(View.VISIBLE);
            binding.viewPager.setCurrentItem(1);
            binding.tabs.getSelectedTabPosition();
        }
    });
    return view =  binding.getRoot();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;

}

public Bitmap SetBrightness(Bitmap src, int value) {
    // original image size
    int width = src.getWidth();
    int height = src.getHeight();
    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
    // color information
    int A, R, G, B;
    int pixel;

    // scan through all pixels
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < height; ++y) {
            // get pixel color
            pixel = src.getPixel(x, y);
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);

            // increase/decrease each channel
            R += value;
            if(R > 255) { R = 255; }
            else if(R < 0) { R = 0; }

            G += value;
            if(G > 255) { G = 255; }
            else if(G < 0) { G = 0; }

            B += value;
            if(B > 255) { B = 255; }
            else if(B < 0) { B = 0; }

            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}
}

【问题讨论】:

  • 片段在加载 XML tablayout 和 viewpagertt 时花费了很多时间
  • 我在 XML bc 中有大约 2000 行代码,我在 StackOverflow 中无法全部提及
  • 你在onCreateView() 做了很多事情。只需在onCreateView() 中扩展视图并尝试在onViewCreated() 中做其他事情。可能会有帮助。
  • 好的,我会试试这个
  • 它的工作方式与以前不同

标签: android android-viewpager fragment android-tablayout


【解决方案1】:

这个答案有两个部分。

  1. 根据https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies

Android 布局允许您在视图层次结构中嵌套 UI 对象。这种嵌套也会增加布局成本。

您的布局有多个嵌套级别,这可能会给布局带来很大的成本。
使用更灵活的布局(如ConstraintLayout)简化布局可能会降低布局成本。

  1. 有时您只是在创建视图时尝试做太多事情,在后台线程中做一些工作并在完成后更新视图(可选地在执行此操作时放置一个忙碌类型的进度条)

一些想法基于您显示的代码。

而不是使用 SetBrightness 方法扫描图像的每个像素,这可能需要一些时间,具体取决于图像的大小。
在没有调整亮度的情况下将图像添加到布局,启动后台任务调整图像亮度,完成后用调整后的图像替换原始未调整的图像。
这可能在没有繁忙的进度条的情况下完成。

将屏幕外浏览器页面的创建延迟到真正需要它们为止。 在创建 Viewpager 时,不要在 viewpager 中的每个 Fragment 在 onCreateView 中创建它的视图,而是在 Fragment 的 onCreateView 中创建一个占位符视图并在 Fragment 的 onResume 中更新它,这仅在 Fragment 显示在屏幕上时调用(注意这种行为需要最近版本的 Viewpager)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多