如何将构造函数中的嵌套方法分离为单独的方法

问题描述 投票:0回答:1

这更多是一种样式,是一种自学的东西,但是在凌空代码中是侦听器,而我在网上找到的所有代码都只是在构造函数内部嵌套了重写方法。不一定是我在C#背景中习惯的。实际上,对于lambda来说并不太好,匿名方法也没有。

我不知道从哪里开始,因为我现在似乎还不直观。但是我想将嵌套方法分离为各自的方法。或者,如果这是唯一需要的部分,则可能只是覆盖的方法。

    final EditText textView = (EditText) findViewById(R.id.editText);

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://myURL";

    JSONObject postparams = new JSONObject();
    postparams.put("city", "london");
    postparams.put("name", "bob");

    // Request a string response from the provided URL.
    JsonObjectRequest  postRequest = new JsonObjectRequest(Request.Method.POST, url, postparams,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    textView.setText("Success: "+ response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    textView.setText(String.valueOf(error.networkResponse.statusCode));
                }
            }
    );
    // Add the request to the RequestQueue.
    queue.add(postRequest);

我想在同一个类的2个Response参数中命名一个方法,或者可以用它本身来覆盖。可能吗?有点像。

...
JsonObjectRequest  postRequest = new JsonObjectRequest(Request.Method.POST, url, postparams, myResponseListener(JSONObject response), myErrorResponseListener(VolleyError error));
// Add the request to the RequestQueue.
queue.add(postRequest);
}

public void myResponseListener(JSONObject response){
     textView.setText("Success: "+ response.toString());
}
public void myErrorResponseListener(VolleyError error){
    textView.setText(String.valueOf(error.networkResponse.statusCode));
}

是否有简单的方法来处理类似的事情?

编辑:尝试linucksrox答案,令我惊讶的是,以下内容实际上是其自身的方法...没有public(访问修饰符)或void(返回类型)??

    Response.Listener<JSONObject> myListener(JSONObject response)
    {
        return new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                textView.setText("Success: "+ response.toString());
            }
        };
    }

但是当我尝试将myListener作为第4个参数插入时,它会抱怨这些参数。

myListener() no work, 
myListener(JSONOBject response) no work

与错误部分参数相同。

java android function methods android-volley
1个回答
0
投票

我现在正在移动设备上,因此我无法确认语法,但是您应该能够做到这一点。有点像

Response.Listener<JSONObject> myListener = new Response.Listener<JSONObject>() {
    @Override public void
    onResponse(JSONObject response) {
        textView.setText("Success: "+ response.toString());
    }
}

然后只需传递myListener

© www.soinside.com 2019 - 2024. All rights reserved.