package com.efounder.chat.activity;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.efounder.chat.R;
import com.efounder.frame.baseui.EFActivity;

/**
 * 通用的跳转Fragment Activity
 * @author hudq
 *
 */
public class TransformFragmentActivity extends EFActivity {
	
	public static final String EXTRA_FRAGMENT_NAME = "fragmentName";
	
	private String fragmentName;
	private Fragment fragment;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_transform_fragment);
		fragmentName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME);
		
		try {
			fragment = (Fragment) Class.forName(fragmentName).newInstance();
			fragment.setArguments(getIntent().getExtras());
			FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
			transaction.add(R.id.fragment_container, fragment);
			transaction.commit();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public void back(View view) {

		finish();
	}

	@Override
	// 设置回退
	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && fragment instanceof OnKeyBackListener) {
			OnKeyBackListener onKeyBackListener = (OnKeyBackListener) fragment;
			boolean forbidPropagate  = onKeyBackListener.OnKeyBack(keyCode, event);
			if (forbidPropagate) {
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 点击返回按钮的监听
	 * @author hudq
	 *
	 */
	public interface OnKeyBackListener{
		/**
		 * 点击返回
		 * @param keyCode KeyEvent.KEYCODE_BACK
		 * @param event 
		 * @return 返回true,防止事件进一步传播,否则，表明你没有处理这个事件,它会继续传播。
		 */
		public boolean OnKeyBack(int keyCode, KeyEvent event);
	}	

}
