如何在我的mainactivity中使用片段中的ImageViews

时间:2019-04-03 00:57:11

标签: java android html android-fragments

所以我有一个带有ImageViews的SettingsActivity / layout,可以将图像从我的手机库上传到这些ImageViews,然后再将它们上传到firebase。当前有3个编辑视图,并且一切正常,直到我想尝试以下操作为止:

现在,我希望有能力在满足某些条件时增加ImageViews的数量。为此,我决定将ImageViews从此活动移至片段活动,然后我创建了另一个ImageViews加倍的活动。这些ImageView的上载/下载的所有代码都在SettingsActivity中进行。最好的方法是什么?我尝试将所有代码移到片段活动中,但最终遇到了太多问题。在SettingsActivity中的片段中使用这些图像视图的最佳方法是什么(我有onclick侦听器和其他需要图像视图的东西):

SettingsActivity.Java

    public class SettingsActivity extends AppCompatActivity {

        private ImageView mImage1, mImage2, mImage3;
        private String image1Url, image2Url, image3Url;

        public static FragmentManager fragmentManager;

        final int MaxTags = 5;
        private int MaxImages = 3;

        @Override
        protected void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_settings);

            fragmentManager = getSupportFragmentManager();
            if(findViewById(R.id.profileImageContainer) != null){
                if(savedInstanceState!=null)
                    return;
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                SettingsDefault settingsDefault = new SettingsDefault();
                fragmentTransaction.add(R.id.profileImageContainer, settingsDefault, null);
                fragmentTransaction.commit();
            }

    getUserInfo();

            mImage1 = findViewById(R.id.image1);
            mImage2 = findViewById(R.id.image2);
            mImage3 = findViewById(R.id.image3);

            mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);

            mImage1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 1);
                }
            });
            mImage2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 2);
                }
            });
            mImage3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 3);
                }
            });

        ArrayAdapter<String> values;
        private void getUserInfo() {

            mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){


                        Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                        if(map.get("phone") != null){
                            phone = map.get("phone").toString();
                            mPhoneField.setText(phone);
                        }
                        if(map.get("sex") != null){
                            userSex = map.get("sex").toString();
                        }

                        Glide.clear(mImage1);
                        if(map.get("image1Url") != null){
                            image1Url = map.get("image1Url").toString();
                            switch(image1Url){
                                case "default":
                                    mImage1.setImageResource(R.mipmap.ic_launcher);

                                    break;
                                default:
                                    Glide.with(getApplication()).load(image1Url).into(mImage1);
                                    break;
                            }
                        }
                        if(map.get("image2Url") != null){
                            image2Url = map.get("image2Url").toString();
                            switch(image2Url){
                                case "default":
                                    mImage2.setImageResource(R.mipmap.ic_launcher);

                                    break;
                                default:
                                    Glide.with(getApplication()).load(image2Url).into(mImage2);
                                    break;
                            }
                        }
                        if(map.get("image3Url") != null){
                            image3Url = map.get("image3Url").toString();
                            switch(image3Url){
                                case "default":
                                    mImage3.setImageResource(R.mipmap.ic_launcher);
                break;
                                default:
                                    Glide.with(getApplication()).load(image3Url).into(mImage3);
                                    break;
                            }
                        }
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }




        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == 1 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image1");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image1Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage1.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }

            }
            if(requestCode == 2 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image2");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image2Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage2.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }
            }
            if(requestCode == 3 && resultCode == Activity.RESULT_OK){
                final Uri imageUri = data.getData();
                final Uri resultUri = imageUri;
                if(resultUri != null){
                    final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image3");
                    Bitmap bitmap = null;

                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
                    byte[] databytes = baos.toByteArray();
                    UploadTask uploadTask = filePath.putBytes(databytes);
                    uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    });
                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Map newImage = new HashMap();
                                    newImage.put("image3Url", uri.toString());
                                    mUserDb.updateChildren(newImage);
                                    mImage3.setImageURI(resultUri);
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {
                                    Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                }
                            });
                        }
                    });

                }else{
                    finish();
                }
            }
        }
    }

SettingsDefault.Java(片段)

public class SettingsDefault extends Fragment {

    ImageView mImageView1;
    ImageView mImageView2;
    ImageView mImageView3;

    public SettingsDefault() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_settings_default, container, false);
        mImageView1 = view.findViewById(R.id.image1);
        mImageView2 = view.findViewById(R.id.image2);
        mImageView3 = view.findViewById(R.id.image3);
        return view;
    }

    public ImageView getImageView1(){
        return  mImageView1;
    }
    public ImageView getImageView2(){
        return  mImageView2;
    }
    public ImageView getImageView3(){
        return  mImageView3;
    }

片段的布局(将ImageViews从SettingsActivity移动到此处)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".Fragments.ProfileImages.SettingsUpgade1">

    <!-- TODO: Update blank fragment layout -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="10sp"
        android:weightSum="3">


        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image1"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"
            />
        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image2"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"

            />
        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image3"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"
            />
        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image4"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"
            />
        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image5"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"

            />
        <ImageView
            android:layout_weight="0.5"
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:id="@+id/image6"
            android:src="@mipmap/ic_launcher"
            android:layout_margin="20sp"
            android:scaleType="centerCrop"
            />

    </LinearLayout>

</FrameLayout>

2 个答案:

答案 0 :(得分:0)

很简单!只需在您的活动和片段之间使用接口即可!!像下面的这个链接一样!

Communicating between a fragment and an activity - best practices

答案 1 :(得分:0)

感谢您提供信息。曾经看过使用似乎对简单任务有用的界面,但是随着活动中大量的imageviews的出现,它变得非常混乱,并且很难理解如何将界面与该应用程序结合使用。为了简化我的生活,我成功地设法将所有利用ImageViews的方法移至片段活动。现在,我将对其他片段执行相同的操作(唯一的区别是它具有两倍的imageviews),并且将使用bolean或其他东西在片段之间滑动。不知道这是否是最好的方法,特别是在性能方面,但是我运行了该应用程序,似乎还可以。