我一直在寻找有关此问题的答案,尽管有许多类似的主题,但没有一种解决方案适合我的需求。我在MainActivity中有此代码,并且可以在其中使用,但是我需要在另一个活动中调用相同的“ addPlayer”方法。
我也尝试过创建一个名为'AddPlayer.java'的新Java类,以通过每个按钮中的两个活动进行调用,但是我找不到一种调用方法。也许是以我定义.java类的方式?
public class AddPlayer extends AppCompatActivity {
public void addPlayer (View view) {
// followed by same content as method in MainActivity - edited to correct contexts
MainActivity代码
public class MainActivity extends AppCompatActivity {
public void addPlayer (View view) {
final ParseObject players = new ParseObject("Players");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog.Builder builderInBuilder = new AlertDialog.Builder(this);
final EditText nameInput = new EditText(this);
nameInput.setInputType(InputType.TYPE_CLASS_TEXT);
final EditText nickInput = new EditText(this);
nickInput.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setTitle("New Player Details")
.setMessage("Enter new player name...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nameInput)
.setPositiveButton("Add Player", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
builderInBuilder.setTitle("New Player Details")
.setMessage("Enter player Nickname...")
.setIcon(android.R.drawable.gallery_thumb)
.setView(nickInput)
.setPositiveButton("Add Nickname", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
players.add("nickname", nickInput.getText().toString());
players.add("username", nameInput.getText().toString());
players.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Player could not be added.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Player added successfully.", Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Add New Player cancelled.", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.show();
}
我在MainActivity中调用该方法没有错误,只是不确定如何从2个活动中最好地调用此方法以及调用单独的Java类所需的语法-该类具有正确的包分配。
我希望能够使用
AddPlayer.addPlayer(); // or something similar
也许最好的方法就是在两个位置都包含此代码?似乎效率低下...
答案 0 :(得分:1)
创建类以执行任务并调用
class AddPlayer{
public void player(Context ctx,View view){
//do your work here
}
}
然后像这样调用该方法
AddPlayer addp = new AddPlayer ();
addp.player(context,view);
我认为概念就是这样,如果您不想创建一个新实例来调用该方法,则可以将该方法声明为静态