Android中在fragment A里面点击button跳转到fragment B实现方法

  • 方法一:直接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();
      			}
      		});
      	}
      }
    
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页