欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Activity跳转到Fragment的方法

程序员文章站 2022-05-28 22:43:39
...

activity不能直接用Intent跳转fragment,因此要用个例外的办法处理。

刚好我的Activity有个gridView,而这个gridVIew点击里面的图片时,适当跳转到对应的fragment。

我的方法是先跳到一个新的Activity里,然后根据这个Activity跳转

以下是android代码,这个是跳转中转的类,利用这个类里面的FrameLayout,直接加载你的fragment(其实相当于是将fragment嵌套在Activity里面) ,不过要将类名传递给这个中转类

 

public class MyFragment extends FragmentActivity {
	public String className = "";
	public FrameLayout frameLayout;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.sys_chg_fragment);  
        init();//初始化
		getValue();//获取类名
		if(StringUtils.isNotEmpty(className)){
			//由于广泛用了Fragment,因此,这里要用这个方法调用
			FragmentManager fm =  getSupportFragmentManager(); 
			// 开启Fragment事务  
	        FragmentTransaction transaction = fm.beginTransaction(); 
	        try{
	        	Class<?> fragClass = Class.forName(className);//反射动态获取类
	        	Object obj = fragClass.newInstance();
	        	Fragment fragment = (Fragment)obj;//类型转换为Fragment
	        	//跳转
	             transaction.replace(R.id.chg_fragment$framelayout, fragment);  
	             transaction.commit();
	        }catch(Exception e){
	        	Logger.error("##############", e, "class error");
	        }
	        
	       
		}
	}

	public void init(){
		//初始化
		frameLayout = (FrameLayout)findViewById(R.id.chg_fragment$framelayout);
	}
	
	//获取传入值
	public void getValue(){
		Intent intent =getIntent();
		className =  intent.getExtras().getString("className");
	}
}