【发布时间】:2023-04-09 03:53:01
【问题描述】:
我有一个Fragment (CreaStanzaFragment) 和一个ImageButton。
这个ImageButton 有一张照片。
现在,当我单击此图像按钮时,他打开了一个新课程(画廊,一个包含大量图像的活动)。当我单击其中一张图片时,我需要更改 ImageButton(在片段中)并使用 imagebutton 中的这张新图片打开此片段。
CreaStanzaFragment 属于一个导航抽屉。 这是片段代码:
public class CreaStanzaFragment extends Fragment {
public CreaStanzaFragment(){}
ImageButton icon;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_log_creastanza, container, false);
return rootView;
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
icon = (ImageButton) view.findViewById(R.id.newicon);
icon.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getContext(), Galleria.class));
}
});
}
这里我只发布Galleria的重要部分
public class Galleria extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_main); //where all the images are located
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// ......
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
@Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
Image image = images.get(position);
String ilnome = inomi.get(position);
Log.i("ILNOME", ilnome);
// What i need to do here to change pictures of ImageButton? How can i open Fragment?
ImageButton icon = (ImageButton) findViewById(R.id.newicon); //loceted in Fragment (CreaStanzaFragment)
imageButton.setBackgroundResource(0);
Glide.with(getApplicationContext()).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageButton);
fragmentTransaction.commit();
}
使用此代码:
setContentView(R.layout.activity_log_creastanza);
ImageButton imageButton = (ImageButton) findViewById(R.id.newicon);
imageButton.setBackgroundResource(0);
Glide.with(getApplicationContext()).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageButton);
当我打开 CreaStanzaFragment 时:
当我点击蓝色图片时(打开 Galleria 活动)
当我点击其中一张图片时:
为什么?
【问题讨论】:
-
如果您在 Gallery Activity 中使用
setContentView,它很可能会用您的 Fragment 的内容替换 Gallery Activity 视图。ImageButton icon = (ImageButton) findViewById(R.id.newicon)也不会在 Fragments 视图层次结构中搜索,而是在Galleria.this.view中搜索。因此,在Galleria中,您只需要引用当前的CreaStanzaFragment或ImageButton,以便Galleria可以访问它的视图并更改按钮背景。 -
但是,我该怎么做呢?能给我举个例子吗?
-
我会尝试写一个示例作为答案
标签: android android-fragments android-imagebutton