Android使用意图从活动中打开片段

Shi*_*lla 6 android android-gridview android-fragments

我正在实现一个应用程序,它在一个活动中包含图像的网格视图,每个图像包含一个片段,其中包含全屏图像.当我点击网格中的任何图像时,它应该打开相应的片段.但是,我们不能使用意图来做到这一点.这是我的代码

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);
            }
Run Code Online (Sandbox Code Playgroud)

而片段是

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此片段绑定到活动ImagesSwipe.那么我如何实现网格视图项与其相应片段之间的转换.谢谢

Ste*_*ett 6

一个图像不需要一个片段.只需在每个图像的布局中重复使用一个带有ImageView的片段.

片段不会像通过Intent一样调用.它们只能作为Activity的一部分存在,这就是它们的设计目标.将它们视为可重用的UI-Modul for Activity.要向活动添加片段,您必须使用FragmentManagerFragmentTransaction类,它们提供与片段的所有交互.

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(YourFragment.newInstance(), null);
    ft.commit();
Run Code Online (Sandbox Code Playgroud)

请参阅Google Docs中的指南,其中介绍了有关GridViews的基本知识.另外你应该阅读有关碎片的内容.这是一个关于你的方法的教程.