Android過時方法替代

weixin_34148456發表於2017-11-14

看見有人推薦了Alibaba Java Coding Guidelines
就安裝了一下這個外掛,發現好多問題啊。
很多時候copy前輩們的程式碼,有很多都過時了,
下面總結一下過時的替代,提醒自己糾正錯誤寫法

getColor()

ContextCompat.getColor(context, R.color.my_color)

getDrawable()

ContextCompat.getDrawable(context, R.color.my_color)

setBackgroundDrawable()

view.setBackgroundResource(R.drawable.status_question);

android.text.ClipboardManager

android.content.ClipboardManager替代,
同樣被廢棄還有setText/getText/hasText方法,
使用setPrimaryClip/getPrimaryClip/hasPrimaryClip

Build.VERSION.SDK

Build.VERSION.SDK_INT

getWidth()和getHeight()

Point size = new Point(); 
activity.getWindowManager().getDefaultDisplay().getSize(size); 
int width = size.x; 
int height = size.y;

mViewPager.setOnPageChangeListener(this);

addOnPageChangeListener

getAllNetworkInfo()

public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Network[] networks = connectivity.getAllNetworks();
        NetworkInfo networkInfo;
        for (Network mNetwork : networks) {
            networkInfo = connectivity.getNetworkInfo(mNetwork);
            if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                return true;
            }
        }
    } else {
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }

        }
    }

    return false;
}}

onAttach

 public void onAttach(Context context)

android.text.ClipboardManager

android.content.ClipboardManager;
cmb.setText(content.trim());
cmb.setPrimaryClip(ClipData.newPlainText(null, content.trim()));
cmb.getText();
cmb.getPrimaryClip().getItemAt(0).getText();

getColorStateList(resId)

ContextCompat.getColorStateList(getContext(), resId);

相關文章