Android how to pass an Activity.class as an argument for a function

后端 未结 7 2256
南方客
南方客 2021-02-12 12: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 parameter

相关标签:
7条回答
  • 2021-02-12 12:30

    If you just want to pass a reference to your Activity use: MakeCall.this (or maybe just this.)

    0 讨论(0)
  • 2021-02-12 12:33

    You need the instance. Use this or SampleActivity.this.

    0 讨论(0)
  • 2021-02-12 12:39

    In Java, each class you write will also have a Class class attached to it. The Class class will be used by the classloader etc.

    As others have said you should use MakeCall.this instead of MakeCall.class because MakeCall.this will point to itself which is an Activity whilst MakeCall.class will point to MakeCall's attached Class class.

    0 讨论(0)
  • 2021-02-12 12:40

    This works for me:

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

    Call the function like this: switchActivity(DestinationActivity.class)

    0 讨论(0)
  • 2021-02-12 12:43

    I think you want to pass this. If this doesn't work, use MakeCall.this.

     getAlertDialog(strArray, strTitle, this).show();
    
    0 讨论(0)
  • 2021-02-12 12:52

    call like this:

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

    Definition:

    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);
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题