编辑
管理Activity和Fragment的有效方式
本文访问次数:0

从零学习安卓开发三个月了(其实也是从零学习Java语言),我对Activity和Fragment的生命流程以及协作方式已经基本了解。
从我看的第一本安卓教程:Android权威编程指南中,我学到了使用Activity管理Fragment,用Fragment封装业务和逻辑代码的交互方式
现在将这种协作方式封装起来,确保符合DRY原则。下面为CommonAcitvity的关键代码:

/**
 * Created by zongren on 2016/3/17.
 */
public abstract class CommonActivity extends AppCompatActivity {
    private static final String TAG = "CommonActivity";

    protected Fragment mFragment;
    protected FragmentManager mFragmentManager;
    protected InputMethodManager mInputManager;
    protected ActionBar mActionBar;
    protected int mLayoutId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentManager = getSupportFragmentManager();
        if (mLayoutId == 0) {
            mLayoutId = R.layout.activity_common;
        }
        setContentView(mLayoutId);
        mFragment = mFragmentManager.findFragmentById(R.id.activity_single_fragment_container);
        if (mFragment == null) {
            mFragment = createFragment();
            mFragmentManager.beginTransaction().add(R.id.activity_single_fragment_container, mFragment).commit();
        }
        mActionBar = getSupportActionBar();
        if (mActionBar != null) {
            mActionBar.setDisplayShowTitleEnabled(true);
            mActionBar.setDisplayHomeAsUpEnabled(true);
            mActionBar.setDisplayShowHomeEnabled(true);
        }
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void onEvent(CustomEvent event) {
        switch (event.getWhat()) {
            default:
                Log.i(TAG, "event " + event.getWhat().toString() + " triggered,message is " + event.getMessage());
                break;
        }
    }

    protected abstract CommonFragment createFragment();

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                mInputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

}

以上的Activity依赖了若干个第三方库,以下为CommonFragment代码

/**
 * Created by zongren on 2016/3/16.
 */
public abstract class CommonFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "CommonFragment";
    protected int mLayoutId;
    protected CustomDialog mWaitDialog;
    protected RequestQueue mRequestQueue;
    protected ImageLoader mImageLoader;
    protected LayoutInflater mInflater;

    private OnResponseListener<String> mRequestListener = new OnResponseListener<String>() {
        @Override
        public void onStart(int what) {
            mWaitDialog.show();
            onRequestStart(HTTP_WHAT.valueOf(what));
        }

        @Override
        public void onSucceed(int what, Response<String> response) {
            onRequestSucceed(HTTP_WHAT.valueOf(what), response.get());
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            onRequestFailed(HTTP_WHAT.valueOf(what), url, tag, exception, responseCode, networkMillis);
        }

        @Override
        public void onFinish(int what) {
            mWaitDialog.dismiss();
            onRequestFinish(HTTP_WHAT.valueOf(what));
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLayoutId = R.layout.fragment_common;
        mWaitDialog = new CustomDialog(getActivity());
        mRequestQueue = NoHttp.newRequestQueue(1);
        EventBus.getDefault().register(this);
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
                showImageForEmptyUri(R.mipmap.pl_universal_image)
                .cacheInMemory(true).cacheOnDisk(true).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getActivity()).defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
        mImageLoader = ImageLoader.getInstance();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(mLayoutId, container, false);
        ButterKnife.bind(this, v);
        mInflater = inflater;
        return v;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mRequestQueue.stop();
        mRequestQueue.cancelAll();
        super.onDestroy();
    }

    public void addRequest(CommonRequest commonRequest) {
        mRequestQueue.add(commonRequest.getWhat().getValue(), commonRequest, mRequestListener);
    }

    protected void onRequestStart(HTTP_WHAT what) {
        switch (what) {
            default:
                Log.i(TAG, "Request start,what is " + what.getValue());
                break;
        }
    }

    protected void onRequestSucceed(HTTP_WHAT what, String response) {
        switch (what) {
            default:
                Log.i(TAG, "Request succeed,what is " + what.getValue() + ",response is " + response);
                break;
        }
    }

    protected void onRequestFailed(HTTP_WHAT what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
        switch (what) {
            default:
                Log.i(TAG, "Request failed,what is " + what.getValue() + ",url is " + url + ",exception is " + exception.getMessage() + ",responseCode is " + responseCode);
                break;
        }
    }

    protected void onRequestFinish(HTTP_WHAT what) {
        switch (what) {
            default:
                Log.i(TAG, "Request finish,what is " + what.getValue());
                break;
        }
    }

    @Subscribe
    public void onEvent(CustomEvent event) {
        switch (event.getWhat()) {
            default:
                Log.i(TAG, "event " + event.getWhat().toString() + " triggered,message is " + event.getMessage());
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }
}

以上Fragment同样依赖了若干个第三方库

需要输入验证码才能留言

没有任何评论