使用 MutableLiveData 和具有多个图像的 LiveData 实现 ViewModel

问题描述 投票:0回答:0

下面的代码使我能够从手机图片库中最多选择 4 张图片。但是,我需要有关视图模型代码的帮助。如果选择了一张图像并且手机配置发生了变化,则该图像会保留下来。但是,如果选择了多张图像,则只有一张图像会保留,所有其他图像都会消失。我需要帮助才能知道我在 viewmodel 代码上做错了什么。在没有视图模型的情况下,所有其他代码都按预期运行良好。添加视图模型以在手机配置更改时为图像添加持久性。我在下面附上了我的代码。

这是选择图像的java代码

'''    
public class MakingFamzFragment extends Fragment {

    ActivityResultLauncher<PickVisualMediaRequest> pickMedia = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(4),
            new ActivityResultCallback<List<Uri>>() {
        @Override
        public void onActivityResult(List<Uri> result) {

            Intent intent = new Intent();
            Intent intent2 = new Intent();
            Intent intent3 = new Intent();
            Intent intent4 = new Intent();

            if(result.size() == 1){
                // Code for when only one picture is picked
                //Capturing the activity result Uri in the Intent
                intentOne = intent.setData(result.get(0));
                //Create ContentResolver to convert the Uri to Bitmap
                cr = requireContext().getContentResolver();
                try {
                    bitmapOne = MediaStore.Images.Media.getBitmap(cr, intentOne.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (isbitmapOne(bitmapOne)) {
                    //Capturing the first image in ImageViewOne using Glide
                    ImageViewOne = binding.editBeforePostingOne;
                    ImageViewOne.setImageBitmap(bitmapOne);
                    Glide.with(requireActivity())
                            .load(bitmapOne)
                            .centerCrop()
                            .into(ImageViewOne);
                    ImageViewOne.setVisibility(View.VISIBLE);
                    viewModel.setImageL(Collections.singletonList(bitmapOne));
                }

            }else if(result.size() == 2){

                // Codes for only when two pictures are picked
                intentOne = intent.setData(result.get(0));
                intentTwo = intent2.setData(result.get(1));
                //Create ContentResolver to convert the Uris to Bitmap
                cr = requireContext().getContentResolver();
                try {
                    bitmapOne = MediaStore.Images.Media.getBitmap(cr, intentOne.getData());
                    bitmapTwo = MediaStore.Images.Media.getBitmap(cr, intentTwo.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (isbitmapOne(bitmapOne) && isbitmapTwo(bitmapTwo)) {
                    //Capturing the first image in ImageViewOne using Glide
                    ImageViewOne = binding.editBeforePostingOne;
                    ImageViewOne.setImageBitmap(bitmapOne);
                    Glide.with(requireActivity())
                            .load(bitmapOne)
                            .centerCrop()
                            .into(ImageViewOne);
                    ImageViewOne.setVisibility(View.VISIBLE);
                   viewModel.setImageL(Collections.singletonList(bitmapOne));

                    //Capturing the second image in ImageViewTwo using Glide
                    ImageViewTwo = binding.editBeforePostingTwo;
                    ImageViewTwo.setImageBitmap(bitmapTwo);
                    Glide.with(requireActivity())
                            .load(bitmapTwo)
                            .centerCrop()
                            .into(ImageViewTwo);
                    ImageViewTwo.setVisibility(View.VISIBLE);
                   viewModel.setImageL(Collections.singletonList(bitmapTwo));
                }

            }else if(result.size() == 3){
                //Codes for only when three pictures are picked
                intentOne = intent.setData(result.get(0));
                intentTwo = intent2.setData(result.get(1));
                intentThree = intent3.setData(result.get(2));
                //Create ContentResolver to convert the Uris to Bitmap
                cr = requireContext().getContentResolver();
                try {
                    bitmapOne = MediaStore.Images.Media.getBitmap(cr, intentOne.getData());
                    bitmapTwo = MediaStore.Images.Media.getBitmap(cr, intentTwo.getData());
                    bitmapThree = MediaStore.Images.Media.getBitmap(cr, intentThree.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (isbitmapOne(bitmapOne) && isbitmapTwo(bitmapTwo) && isbitmapThree(bitmapThree)) {
                    //Capturing the first image in ImageViewOne using Glide
                    ImageViewOne = binding.editBeforePostingOne;
                    ImageViewOne.setImageBitmap(bitmapOne);
                    Glide.with(requireActivity())
                            .load(bitmapOne)
                            .centerCrop()
                            .into(ImageViewOne);
                    ImageViewOne.setVisibility(View.VISIBLE);
                   viewModel.setImageL(Collections.singletonList(bitmapOne));

                    //Capturing the second image in ImageViewThree using Glide
                    ImageViewTwo = binding.editBeforePostingTwo;
                    ImageViewTwo.setImageBitmap(bitmapTwo);
                    Glide.with(requireActivity())
                            .load(bitmapTwo)
                            .centerCrop()
                            .into(ImageViewTwo);
                    ImageViewTwo.setVisibility(View.VISIBLE);
                  viewModel.setImageL(Collections.singletonList(bitmapTwo));

                    //Capturing the third image in ImageViewThree using Glide
                    ImageViewThree = binding.editBeforePostingThree;
                    ImageViewThree.setImageBitmap(bitmapThree);
                    Glide.with(requireActivity())
                            .load(bitmapThree)
                            .centerCrop()
                            .into(ImageViewThree);
                    ImageViewThree.setVisibility(View.VISIBLE);
                    viewModel.setImageL(Collections.singletonList(bitmapThree));
                }

            }

        }
        });
    

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //Instantiatiate the binding class
        binding = FragmentMakingFamzBinding.inflate(getLayoutInflater());

        //Instantiate the viewModel class
        viewModel = new ViewModelProvider(this.requireActivity()).get(MyViewModel.class);

        // binding the multiautocompletetextiview as famzMakinglayout and implement the textcount found in it
        //to count the number of text typed in it
        fmzMakingLayout = binding.multiAutocompleteTextview;
        textCount = binding.textCount;
        fmzMakingLayout.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ch = String.valueOf(fmzMakingLayout.getText().toString().length());
                textCount.setText(ch);
                System.out.println(ch);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel.getImage().observe(getViewLifecycleOwner(), new Observer<List<Bitmap>>() {
            @Override
            public void onChanged(List<Bitmap> bitmap) {
                if(bitmap.size() == 1){

                bitmapOne = bitmap.get(0);

                ImageViewOne = binding.editBeforePostingOne;
                ImageViewOne.setImageBitmap(bitmapOne);
                Glide.with(requireContext())
                        .load(bitmapOne)
                        .centerCrop()
                        .into(ImageViewOne);
                ImageViewOne.setVisibility(View.VISIBLE);

                }else if(bitmap.size() == 2) {

                    bitmapOne = bitmap.get(0);

                    ImageViewOne = binding.editBeforePostingOne;
                    ImageViewOne.setImageBitmap(bitmapOne);
                    Glide.with(requireContext())
                            .load(bitmapOne)
                            .centerCrop()
                            .into(ImageViewOne);
                    ImageViewOne.setVisibility(View.VISIBLE);

                    bitmapTwo = bitmap.get(1);

                    ImageViewTwo = binding.editBeforePostingTwo;
                    ImageViewTwo.setImageBitmap(bitmapTwo);
                    Glide.with(requireContext())
                            .load(bitmapTwo)
                            .centerCrop()
                            .into(ImageViewTwo);
                    ImageViewTwo.setVisibility(View.VISIBLE);
                }



            }
        });


        binding.famzingBottomNavigation.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                // Defining local final ids
                final int id1 = R.id.famzing_add_pictures;
                final int id2 = R.id.famzing_files;
                final int id3 = R.id.famzing_emoji;
                final int id4 = R.id.famzing_giff;

                switch (item.getItemId()) {
                    case id1:
                        Intent iGallery = new Intent(Intent.ACTION_PICK);
                        iGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        iGallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        pickMedia.launch(pick);

                        Toast.makeText(getContext(), "Add picture selected", Toast.LENGTH_SHORT).show();
                        break;
                    case id2:
                        Toast.makeText(getContext(), "Add files selected", Toast.LENGTH_SHORT).show();
                        break;
                    case id3:
                        Toast.makeText(getContext(), "Add emoji selected", Toast.LENGTH_SHORT).show();
                        break;
                    case id4:
                        Toast.makeText(getContext(), "Add giff selected", Toast.LENGTH_SHORT).show();
                        break;
                }

                return false;
            }
        });
    }
}
'''

This is the viewmodel code
---------------------------

'''

public class MyViewModel extends ViewModel {

    public MutableLiveData<List<Bitmap>> imageL = new MutableLiveData<>();

    public void setImageL(List<Bitmap> bitmapOne){
        imageL.postValue(bitmapOne);

    }

    public LiveData<List<Bitmap>> getImage(){
        return imageL;
    }


    @Override
    protected void onCleared() {
        super.onCleared();
    }
}

'''

这是包含图像视图的片段的 xml 代码

发送到

'''
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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/famz_making_page"
    android:layout_width="match_parent"

    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"

    android:background="@color/white"

    android:orientation="vertical"
    tools:context=".MakingFamzFragment">

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:gravity="top"
        android:orientation="horizontal"
        android:padding="9dp">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginStart="9dp"
            android:layout_marginLeft="9dp"
            android:background="@mipmap/user_profile_image"
            android:contentDescription="@string/profile_picture"
            android:gravity="end">

        </ImageView>

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="start"
                android:layout_marginStart="9dp"
                android:layout_marginLeft="9dp"
                android:text="@string/profile_name"
                android:textSize="12sp">

            </TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="start|bottom"
                android:layout_marginStart="9dp"
                android:layout_marginLeft="9dp"
                android:layout_marginBottom="6dp"
                android:text="@string/profile_username"
                android:textSize="12sp">

            </TextView>
        </LinearLayout>


    </LinearLayout>


    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="2dp"
        android:background="?android:attr/listDivider">

    </View>
  
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/pink"
                android:orientation="vertical">


                <TextView

                    android:id="@+id/text_count"
                    android:layout_width="39dp"
                    android:layout_height="15dp"
                    android:layout_gravity="end"
                    android:layout_marginTop="2dp"
                    android:layout_marginEnd="9dp"
                    android:layout_marginRight="9dp">

                </TextView>

                <MultiAutoCompleteTextView
                    android:id="@+id/multi_autocomplete_textview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="6dp"
                    android:autoLink="all"
                    android:background="@color/transparent"
                    android:bufferType="normal"
                    android:fitsSystemWindows="true"
                    android:fontFamily="sans-serif"
                    android:hint="@string/write_here"
                    android:linksClickable="true"
                    android:maxLength="500"
                    android:padding="8dp"
                    android:selectAllOnFocus="true"
                    android:textColorLink="#2596be"
                    android:textSize="16sp"
                    tools:ignore="TouchTargetSizeCheck">

                </MultiAutoCompleteTextView>

                <HorizontalScrollView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">


                <RelativeLayout

                    android:id="@+id/relate_make_post_frag"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="200dp"
                        android:layout_height="150dp"
                        android:id="@+id/edit_Before_Posting_One"
                        android:contentDescription="@string/image_number_one"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:layout_marginEnd="2dp"
                        android:layout_marginRight="2dp"
                        android:visibility="gone"/>
                    <ImageView
                        android:layout_width="200dp"
                        android:layout_height="150dp"
                        android:id="@+id/edit_Before_Posting_Two"
                        android:contentDescription="@string/image_number_two"
                        android:layout_toRightOf="@id/edit_Before_Posting_One"
                        android:layout_toEndOf="@id/edit_Before_Posting_One"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:layout_marginEnd="2dp"
                        android:layout_marginRight="2dp"
                        android:visibility="gone"/>
                    <ImageView
                        android:layout_width="200dp"
                        android:layout_height="150dp"
                        android:id="@+id/edit_Before_Posting_three"
                        android:contentDescription="@string/image_number_three"
                        android:layout_toRightOf="@id/edit_Before_Posting_Two"
                        android:layout_toEndOf="@id/edit_Before_Posting_Two"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:layout_marginEnd="2dp"
                        android:layout_marginRight="2dp"
                        android:visibility="gone"/>
                    <ImageView
                        android:layout_width="200dp"
                        android:layout_height="150dp"
                        android:id="@+id/edit_Before_Posting_Four"
                        android:contentDescription="@string/image_number_four"
                        android:layout_toRightOf="@id/edit_Before_Posting_three"
                        android:layout_toEndOf="@id/edit_Before_Posting_three"
                        android:layout_marginStart="2dp"
                        android:layout_marginLeft="2dp"
                        android:layout_marginEnd="2dp"
                        android:layout_marginRight="2dp"
                        android:visibility="gone"/>

                </RelativeLayout>

                </HorizontalScrollView>


                <View
                    android:layout_width="wrap_content"
                    android:layout_height="1dp"
                    android:layout_marginTop="2dp"
                    android:background="?android:attr/listDivider">

                </View>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:foregroundGravity="top"
                android:background="@color/white">

                <com.google.android.material.bottomnavigation.BottomNavigationView
                    android:id="@+id/famzing_bottom_navigation"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@drawable/makingfamz_elevation"
                    android:fitsSystemWindows="true"
                    app:elevation="7dp"
                    app:itemIconTint="@color/fambuk_green"
                    app:itemTextColor="@color/fambuk_green"
                    app:menu="@menu/famz_making_menu">

                </com.google.android.material.bottomnavigation.BottomNavigationView>

            </LinearLayout>

            <View
                android:layout_width="wrap_content"
                android:layout_height="1dp"
                android:layout_marginTop="2dp"
                android:background="?android:attr/listDivider">

            </View>

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

                <Button
                    style="?android:attr/buttonBarButtonStyle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="4dp"
                    android:layout_marginRight="0.1dp"
                    android:layout_weight="2"
                    android:background="@drawable/submit_post_button_elevation"
                    android:text="@string/post_submit_button"
                    android:textColor="@color/white">

                </Button>

                <Button
                    style="?android:attr/buttonBarButtonStyle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginStart="0.1dp"
                    android:layout_marginLeft="0.1dp"
                    android:layout_weight="2"
                    android:background="@drawable/submit_post_button_elevation"
                    android:text="@string/close_button"
                    android:textColor="@color/white">

                </Button>
            </LinearLayout>

    <View
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:layout_marginTop="2dp"
        android:background="?android:attr/listDivider">

    </View>

</LinearLayout>


</ScrollView>

'''

这是一张图片被选中时的屏幕截图,当手机旋转时会发生什么

注意:当只选择一张图像时,viewmodel 工作正常。 However, when more than one image is selected, the viewmodel does not work properly. 当我选择两个不同的图像时,出现的两个图像是最后一个被选择的图像。第一个没有出现。当它旋转到横向模式时,一个图像消失,片段上只剩下一个。以下是示例屏幕截图:

How can I write the viewmodel code so that when more than one images are picked and the orientation of the phone is changed, all picked images will not disappear from the phone.

viewmodel android-livedata mutablelivedata
© www.soinside.com 2019 - 2024. All rights reserved.