我有一个按钮,其功能的一部分在一个类中,位于同一个包中的另一个类文件中。这是应该如何完成的方式,或者我可以以某种方式传递当前活动的实例,然后使用它在第二类的方法中的任何方法或字段。
public class LogInScreen extends AppCompatActivity {
Button logInButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in_screen);
logInButton = findViewById(R.id.button_login);
userText = findViewById(R.id.editText_user);
passText = findViewById(R.id.editText_pass);
}
public void logIn(View view) {
logInButton.setEnabled(false);
String username = userText.getText().toString();
String password = passText.getText().toString();
BackendConnectionService.encodeCredentials(username, password);
RequestQueue requestQueue = Volley.newRequestQueue(this);
BackendConnectionService.handleSSLHandshake();
// here I put the button
requestQueue.add(BackendConnectionService.createLogInRequest(this, logInButton));
}
}
第二类宣言
public class BackendConnectionService {
// some class declarations
static JsonArrayRequest createLogInRequest(Context packageContext, Button button){
final Context context = packageContext;
final Button b = button;
return new JsonArrayRequest(
Request.Method.GET,
PALLETE_URL,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Intent intent = new Intent(context, PalletsScreen.class);
context.startActivity(intent);
b.setEnabled(true);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST ResponseErr", error.toString());
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
b.setEnabled(true);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(autorisation, encodedCredentials);
return headers;
}
};
}
}
答案 0 :(得分:1)
老实说,你已经做到了:)。你只需要知道如何使用它。我们假设您要在createLogInRequest
方法中使用LogInScreen:
static JsonArrayRequest createLogInRequest(Context packageContext, Button button){
final Context context = packageContext;
final Button b = button;
LogInScreen logInScreen = null;
if(context instanceof LogInScreen) {
logInScreen = (LogInScreen) context;
}
//...
}