android中在fragment A里面点击button跳转到fragment B怎么实现?
2015-12-07 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
方法一:直接getActivity,使用activity的fragmenttransation的replace方法替换
假设
class OneFragment extends Fragment{
private Button btn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_one, null);
btn = (Button)view.findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
fm.beginTransaction()
//替换为TwoFragment
.replace(R.layout.fragment_container,new TwoFragment())
.commit();
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
}
但是这样做会使OneFragment和原activity的耦合度提高,fragment设计出来就是有重用的目的,所以不好,使用方法二
方法2:定义回调函数,当button按下调用回调
class OneFragment extends Fragment{
private Button btn;
private OnButtonClick onButtonClick;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_one, null);
btn = (Button)view.findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(onButtonClick!=null){
onButtonClick.onClick(btn);
}
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
public OnButtonClick getOnButtonClick() {
return onButtonClick;
}
public void setOnButtonClick(OnButtonClick onButtonClick) {
this.onButtonClick = onButtonClick;
}
public interface OnButtonClick{
public void onClick(View view);
}
}
这样只要在acitivty中设置回调即可
public class MainActivity extends Activity {
private OneFragment oneFragment = new OneFragment();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//。。。
//。。。省略代码
oneFragment.setOnButtonClick(new OnButtonClick() {
@Override
public void onClick(View view) {
//切换到TwoFragment
fm.beginTransaction()
//替换为TwoFragment
.replace(R.layout.fragment_container,new TwoFragment())
.commit();
}
});
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询