Android使用 Intent 从 Activity 中打开 fragment

标签 android android-fragments android-gridview

我正在实现一个应用程序,它在一个 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 中,您必须使用 FragmentManagerFragmentTransaction类,提供与 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/

相关文章:

java - 如何创建中间带有单个边框的相邻 Material 按钮

android - 无法在 Kivy 中为动画选择 id

android - 如何在不在设备短信 View 中记录的情况下从 Android 应用程序发送短信?

android - 在android中实现ListView时遇到ClassCastException?

android - GridView 只显示一行

android - 如何从另一个 Activity 调用 Gridview Activity

java - 为什么 MyRequestQueue_Drivers 中这两个字符串(company_id 和branch_id)等于 null?

fragment 内的 Android map

android - 如何使用 Fragment 进行数据绑定(bind)

Android - 寻找有关以编程方式创建类似于电子表格的 GridView 的建议?