22

I recently moved to Android from Python and am stuck here.

This is my class declaration to create a common function for an Alert Dialog which accepts necessary parameters:

public static AlertDialog.Builder getAlertDialog(String strArray[],
        String strTitle, Activity v) {

    return new AlertDialog.Builder(v)
    .setTitle(strTitle).setItems(strArray,
            new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
        }
    });
}

But I cannot call this function via this piece of code which gives me an error:

  getAlertDialog(strArray, strTitle, MakeCall.class).show();

The error is:

the method getAlertDialog(String[], String, Activity) in the type   MakeCallAlertDialog is not applicable for the arguments (String[], String, Class<TestActivity>)

How can I get this correctly?

4

7 回答 7

32

像这样调用:

ButtonClickBySani(R.id.btnsehrabandi, sehrabandiActivity.class);

定义:

private void ButtonClickBySani(int ButtonId, final Class<? extends Activity> ActivityToOpen)
{
    Button btn;
    // Locate the button in activity_main.xml
    btn = (Button) findViewById(ButtonId);

    // Capture button clicks
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            startActivity(new Intent(getBaseContext(), ActivityToOpen));
            // Start NewActivity.class
            //Intent myIntent = new Intent(getBaseContext(), ActivityToOpen);
           // startActivity(myIntent);
        }
    });
}
于 2014-11-06T10:34:38.367 回答
13

如果您只想传递对 Activity 的引用,请使用:(MakeCall.this或者可能只是this.)

于 2013-03-05T16:41:23.033 回答
6

只需创建一个活动对象/实例,如new YourActivity()

public static void Redirect(Context context,Activity page) {

..... //code

context.startActivity(new Intent(context,page.getClass()));

((Activity) context).finish();
}

并将此方法用作

Redirect(Registration.this, new YourActivity());
于 2014-06-23T11:11:21.163 回答
4

我想你想通过this。如果不起作用,请使用MakeCall.this.

 getAlertDialog(strArray, strTitle, this).show();
于 2013-03-05T16:41:13.230 回答
4

你需要实例。使用thisSampleActivity.this

于 2013-03-06T08:38:33.777 回答
1

这对我有用:

private void switchActivity(Class cls){
    Intent intent = new Intent(HomeActivity.this, cls);
    startActivity(intent);
}

像这样调用函数:switchActivity(DestinationActivity.class)

于 2018-04-05T21:02:59.957 回答
0

在 Java 中,您编写的每个类也将Class附加一个类。该类Class将由类加载器等使用。

正如其他人所说,您应该使用MakeCall.this而不是MakeCall.class因为MakeCall.this将指向自身,它是一个活动,同时MakeCall.class将指向 MakeCall 的附加Class类。

于 2013-03-05T16:46:24.190 回答