在Android的Uri.Builder中替换查询参数? [英] Replace query parameters in Uri.Builder in Android?

查看:899
本文介绍了在Android的Uri.Builder中替换查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在传递一个Uri.Builder对象作为子类的一种机制,以便在 Android 中执行Uri之前将所需的任何参数填充到Uri中.

I'm passing around a Uri.Builder object as a mechanism for subclasses to fill in whatever parameters necessary into a Uri before it is executed in Android.

问题是,需要在子类中替换基类使用builder.appendQueryParameter("q",searchPhrase);添加的参数之一,但是我只能找到appendQueryParameter(),没有替换或设置方法.具有相同参数名称的appendQueryParameter()会添加该参数的另一个实例,而不是替换它.

Problem is, one of the parameters that the base class adds using builder.appendQueryParameter("q",searchPhrase); needs to be replaced in the sub-class, but I can only find appendQueryParameter(), there is no replace or set method. appendQueryParameter() with the same parameter name adds another instance of the parameter, doesn't replace it.

我应该放弃并尝试另一种方式吗?还是有办法替换我尚未找到的查询参数?

Should I give up and try another way? Or is there a way to replace query parameters that I haven't found yet?

推荐答案

由于没有内置方法,因此我发现的最佳方法是构建新的Uri.您遍历旧Uri的所有查询参数,然后将所需的键替换为新的值.

Since there is no in-built method, the best way I have found is to build a new Uri. You iterate over all the query parameters of the old Uri and then replace the desired key with the new value.

private static Uri replaceUriParameter(Uri uri, String key, String newValue) {
    final Set<String> params = uri.getQueryParameterNames();
    final Uri.Builder newUri = uri.buildUpon().clearQuery();
    for (String param : params) {
        newUri.appendQueryParameter(param, 
            param.equals(key) ? newValue : uri.getQueryParameter(param));
    }

    return newUri.build();
}

这篇关于在Android的Uri.Builder中替换查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆