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

时间:2016-06-02 05:31:08

标签: android-fragments android-studio android-asynctask android-studio-2.0

我可以在setOnClickListener之外编写fab = (FloatingActionButton)findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TranslateAnimation animation = new TranslateAnimation(400.0f,200.0f,0.0f,0.0f); animation.setDuration(5000); animation.setRepeatCount(1); animation.setRepeatMode(1); fab.startAnimation(animation); } }); ,它可以顺利运行,但我需要在setOnClickListener中编写它。

postAsync = new PostAsync();
                    postAsync.delegate = this;

}

显然写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"); } } 不起作用。你有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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