提示:小美女小帅哥,点个赞点个关注,不秃头
文章目录
Intent踩坑
一、intent跳转编译错误?
使用intent进行页面跳转时候出现BUg`
二、问题原因
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");
}
}