如何在覆盖其中一个方法的同时启动一个Activity?

时间:2017-09-09 04:23:07

标签: java android android-activity override

我有两个课程,两个课程都延伸Activity

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout activityLayout = new LinearLayout(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        activityLayout.setLayoutParams(lp);
        activityLayout.setOrientation(LinearLayout.VERTICAL);
        activityLayout.setPadding(16, 16, 16, 16);
        activityLayout.addView(new Button(this));
        setContentView(activityLayout);

        new Permissions() {
            @Override
            public void onPermissionRefused() {
                Toast.makeText(getBaseContext(), "Refused", Toast.LENGTH_SHORT).show();
            }
        }.requestPermissions(this);
    }
}

Permissions.java

public class Permissions extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme_Dialog); // Custom theme to make Activity like a Dialog
        super.onCreate(savedInstanceState);
        onPermissionRefused();
    }

    public void requestPermissions(Activity activity, String... permissions) {
        startActivity(new Intent(activity, Permissions.class));
    }

    public void onPermissionRefused() {

    }
}

我想要做的是在覆盖Permissions方法的同时启动Activity onPermissionRefused()。但是,我尝试过两种方式都没有。

new Permissions() {
            @Override
            public void onPermissionRefused() {
                Toast.makeText(getBaseContext(), "Refused", Toast.LENGTH_SHORT).show();
            }
        }.requestPermissions(this);

不传递覆盖并将代码交换出来:startActivity(new Intent(this, Permissions.class));甚至不允许我覆盖该方法。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

步骤1.创建权限的子类

class MyPermissionsActivity extends Permissions {
            @Override
            public void onPermissionRefused() {
                Toast.makeText(getBaseContext(), "Refused", Toast.LENGTH_SHORT).show();
            }

}

步骤2.在应用程序清单中声明该子类

步骤3.按如下方式启动活动:

Intent i = new Intent(context, MyPermissionsActivity.class);
currentActivity.startActivity(i);

答案 1 :(得分:0)

你不能。必须在清单中声明活动,你不能以这种方式声明一个匿名的内部类(即使你可以,它也不会因为对父类的隐式引用而拥有正确的构造函数)。如果需要,请创建一个真正的子类,并通过intent传递任何必要的变量。