我正在实现一个应用程序,它在一个 Activity 中有一个图像 GridView ,每个图像都有一个 fragment ,其中包含全屏图像。当我点击网格中的任何图像时,它应该会打开相应的 fragment 。但是,我们不能使用 Intent 来做到这一点。 这是我的代码
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if(position==0)
{
Intent i=new Intent(Gallery.this,ImageFrag1.class);
startActivity(i);
}
fragment 是
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ImageFrag1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.imagefrag1, container, false);
}
}
此 fragment 绑定(bind)到 Activity ImagesSwipe。那么我如何实现 GridView 项与其相应 fragment 之间的转换。 谢谢
最佳答案
一张图片不需要一个 fragment 。只需在每个图像的布局中重复使用一个带有 ImageView 的 fragment 。
Fragments 不像 Activity 那样通过 Intent 被调用。它们只能作为 Activity 的一部分存在,这就是它们的设计目的。将它们视为 Activity 的可重用 UI 模块。要将 fragment 添加到 Activity 中,您必须使用 FragmentManager和 FragmentTransaction类,提供与 fragment 的所有交互。
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(YourFragment.newInstance(), null);
ft.commit();
看看this来自 Google 文档的指南,其中描述了有关 GridView 的基本内容。此外,您应该阅读 Fragments .这是一个 Tutorial关于你的方法。
关于Android使用 Intent 从 Activity 中打开 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556390/