0

I want to change the ImageView in my fragment's xml when I click on an Image from a pop up window class.

Pop Up class

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);
        }
    });
}

This is the imageview from another fragment I want to change upon click.

   <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" />
Enzo
  • 11
  • 2

1 Answers1

0

Welcome to Stack Overflow, @Enzo.

There are a few ways to accomplish what you want.

A traditional way to accomplish this is to use an interface in a dialog fragment.

Some ideas are in this question and set of answers

Callback to a Fragment from a DialogFragment

Another solution would be to use a shared ViewModel. Your picker can set the Drawable and you can use it in your other activity.

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

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

The important part if you go the ViewModel route is to make sure that your two activities or fragments, etc, share the same scope.

Another easy way to accomplish this is to use a Singleton or a Kotlin object. This works well if you only every want one instance that all will read and write to.

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

Cory Roy
  • 5,379
  • 2
  • 28
  • 47