如何将 class 委托给 Async Task 实例?

How to delegate class into an Async Task instance?

我可以将 postAsync = new PostAsync(); postAsync.delegate = this; 写在 setOnClickListener 之外,这将顺利运行,但我需要将其写在 setOnClickListener 内。

public class Sign_inFragment extends Fragment implements AsyncResponse {
PostAsync postAsync;

String email, password, logInResult;
EditText ev, pv;
Button bv;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.sign_in_fragment, container, false);

    bv = (Button) v.findViewById(R.id.signinButton);
    ev = (EditText) v.findViewById(R.id.emailTextView);
    pv = (EditText) v.findViewById(R.id.passwordTextView);

    bv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (ev.getText() != null && pv.getText() != null) {
                email = ev.getText().toString();
                password = pv.getText().toString();

                postAsync = new PostAsync();
                postAsync.delegate = this;//this will not work.
                postAsync.execute(email, password);

                //Toast.makeText(getActivity().getApplicationContext(), "SIGN IN SUCCESFUL", Toast.LENGTH_LONG).show();
            }
        }
    });

    return v;
}

@Override
public void processFinish(String output) {
    logInResult = output;

    if (logInResult.equals("true") ) {
        Intent intent = new Intent(getActivity().getApplicationContext(), SignedInActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    } else if(logInResult.equals("false")) {
        ev.setError("Invalid Account");
    }
}

}

显然写 postAsync.delegate = this 是行不通的。你有什么建议吗?

在您的情况下,this 被视为按钮视图,因为您在 button click 方法中使用它。如果你想传递片段,你必须写成 postAsync.delegate = Sign_inFragment.this 或者如果你想要 activity 那么 postAsync.delegate = getActivity();