如何将类委托给异步任务实例



我可以在setOnClickListener之外写postAsync = new PostAsync(); postAsync.delegate = this;,这将顺利工作,但我需要在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因为您在单击方法中使用它。如果你想传递片段,你必须像postAsync.delegate = Sign_inFragment.this一样写,或者如果你想要活动,那么postAsync.delegate = getActivity();

最新更新