首页 > 解决方案 > 如何从弹出窗口类更改片段中的 ImageView?

问题描述

当我从弹出窗口类中单击图像时,我想更改片段 xml 中的 ImageView。

弹出类

public class MoodPopUp extends Activity {

ImageView a,b,c,d,e,f,g,h,i;
ImageView main;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mood_picker_popup);

    DisplayMetrics  displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;

    //Pop Up Window Size
    getWindow().setLayout((int) (width*.8),(int)(height*.6));

    //Set emoji images on mood imageview
    //Main Mood Image View
    main = (ImageView) findViewById(R.id.MainMoodimageview);

    //Pop Up Picker on Click
    a = (ImageView) findViewById(R.id.Aemoji);
    a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            main.setImageResource(R.drawable.smiling);
        }
    });
}

这是我想在单击时更改的另一个片段的图像视图。

   <ImageView
    android:id="@+id/MainMoodimageview"
    android:layout_width="187dp"
    android:layout_height="163dp"
    android:layout_marginTop="19dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/divider3"
    android:src="@drawable/ic_baseline_emoji_emotions_24" />

标签: javaandroidxmlandroid-studio

解决方案


欢迎来到 Stack Overflow,@Enzo。

有几种方法可以实现您想要的。

实现此目的的传统方法是在对话框片段中使用接口。

这个问题和一组答案中有一些想法

从 DialogFragment 回调片段

另一种解决方案是使用共享的 ViewModel。您的选择器可以设置 Drawable,您可以在其他活动中使用它。

https://developer.android.com/topic/libraries/architecture/viewmodel

https://developer.android.com/codelabs/kotlin-android-training-view-model#0

如果您采用 ViewModel 路线,重要的部分是确保您的两个活动或片段等共享相同的范围。

另一种简单的方法是使用 Singleton 或 Kotlin 对象。如果您只需要一个所有人都可以读取和写入的实例,则此方法效果很好。

https://kotlinlang.org/docs/object-declarations.html#object-declarations


推荐阅读