Java android.util.Pair 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20295526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:54:44  来源:igfitidea点击:

android.util.Pair example

javaandroid

提问by Gert Cuykens

   @Override
    public void onClick(View view) {
        Context context = view.getContext();
        switch(view.getId()) {
            case R.id.getGreetingButton:
                Pair <Context,Integer>p=new Pair(context,1);
                new RestTask().execute(p);
                break;

        }
    }

    private class RestTask extends AsyncTask<Pair<Context,Integer>, Void, Pair<Context,String>> {
        @Override
        protected Pair doInBackground(Pair<Context,Integer>... p) {
            String text = "hello";
            Pair <Context,String>result=new Pair(p.first,text);
            return result;
        }
        @Override
        protected void onPostExecute(Pair<Context,String>... p) {toaster(p.first, p.second);}
    }

1) How do you call this ...thing and what does it do?

1)你怎么称呼这个...东西,它有什么作用?

2) Why are p.first and p.second not found by the compiler?

2)为什么编译器找不到p.first和p.second?

3) When do you use Pair.create(a,b)?

3) 你什么时候使用 Pair.create(a,b)?

采纳答案by ksasq

For 1) please see http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html- it's essentially a variable number of Pairs you are passing in here.

对于 1) 请参阅http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html- 它本质上是您在此处传递的可变数量的对。

2) Use p[0].first and p[0].second, treat the parameter like an array. you could pass many Pairs in your call to execute() and each one becomes an item in the array passed to doInBackground()

2)使用p[0].first和p[0].second,把参数当成数组对待。您可以在调用 execute() 时传递许多 Pairs,并且每个 Pairs 都成为传递给 doInBackground() 的数组中的一项

3) You could use it in your call to execute() as a shorthand to avoid creating the local variable p, and also in doInBackground you could return Pair.create() instead of creating the local result variable. Something like:

3) 您可以在调用 execute() 时使用它作为速记来避免创建局部变量 p,而且在 doInBackground 中,您可以返回 Pair.create() 而不是创建局部结果变量。就像是:

switch(view.getId()) {
        case R.id.getGreetingButton:
            new RestTask().execute(Pair.create(context,1));
            break;

    }