java - 如何从弹出窗口类更改片段中的 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" />
解决方案
欢迎来到 Stack Overflow,@Enzo。
有几种方法可以实现您想要的。
实现此目的的传统方法是在对话框片段中使用接口。
这个问题和一组答案中有一些想法
另一种解决方案是使用共享的 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
推荐阅读
- pandas - 如何根据当前日期查找上个月的数据?
- c++ - 在 Windows 上诊断构成 R 包一部分的 C++ 代码中的内存泄漏
- bash - 路径目录中单个反斜杠后跟空格(“\”)和两个反斜杠之间有空格(“\ \”)有什么区别?
- angularjs - 在angularjs中将属性绑定更改为第三方指令
- java - 拆分字符串但仍显示所有元素
- javascript - 使用正则表达式删除字符串 + 字符
- python - Python 脚本在 Pycharm 上运行,但在 c# 上不使用 Iron Python
- php - 装饰 Shopware6 api 控制器以将 pluginreader 数据保存到实体
- html - 我可以在多个选择下拉菜单中使用相同的选项元素吗?
- regex - 在具有特定值的字符串中查找“~XX~”