Some obsolete but commonly used method replacements for Android

foreword

Because of Google's frequent updates to android, every time I look for some implementation methods, I find that it is actually outdated. Although the official website also has a way to realize it, but it may be insufficient localization or there are no examples for individual methods. Some seem to be difficult, and you have to find some simple examples to understand the usage. I will use this blog to post it. A commonly used method that is not easy to remember

method

1. Get the color in res/values/colors, getColor()

The previous method:

context.getResource().getColor();//已弃用

context.getColor();//方法需要在API23以上才能用

alternative method:

ContextCompat.getColor(context,R.color.red);

2.onActivityResult(), jump to other activities according to intent and get data

The original method:

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

The current method:

private final ActivityResultLauncher<Intent> resultLauncher = 
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        if (result != null && result.getResultCode() == Activity.RESULT_OK ) {
            //todo
        }
    });

//在方法中调用launcher
private void getResult(){
    resultLauncher.launch(intent) 
}

Guess you like

Origin blog.csdn.net/TDSSS/article/details/127762963