如何在Android Studio上调用带有视图参数的方法

问题描述 投票:10回答:4

我想调用此方法

public void openButton(View view) {
    Intent intent = new Intent(this, MainActivity.class);
    this.startActivity(intent);
}

通过这样的简单方法

public void simple(){
    openButton();
}

但是我不能这样做,因为openButton需要一个参数View。怎么样?

java android methods view parameters
4个回答
9
投票

嗯,使用您提供的代码,通常使用某种onCickListener

打开XML文件,然后在要调用该方法的按钮上添加android:onClick="openButton"。因此,您用于按钮的XML如下所示:

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Click me!"
   . . . 
   android:onClick="openButton" />

这将自动调用该方法并传递视图。

正如评论中BatScream所提到的,另一种选择是只传入null,因为无论如何您都不会使用该视图。但是,这不是一个好习惯-这次可以使用,但是一般来说,您应该遵循Android使用的系统。只需在XML中使用onClick


如果您必须按原样使用simple,请按照以下方式进行操作:

public void simple(){
    openButton(null);
}

2
投票

您应该可以这样做

 button.performClick(); 

假设openButton()是分配给buttononClick的方法。意思是,在您的xml中的某个地方,您可能具有Buttonandroid:onClick="openButton"。然后,如果您实例化了Button并将其分配给变量button,则调用ViewperformClick()方法将调用openButton()


0
投票

简单。只需在参数中传递视图即可。

方式1:如果要从布局文件中调用openButton()方法,只需通过应用onClick属性以以下方式调用方法

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Go to next screen"
   . . . 
   android:onClick="openButton" />

方式2:如果您试图通过设置OnClickListener从按钮的onclick调用它,则只需传递您正在OnClickListeneronClick(View view)方法内部的视图,如下所示:

button.setOnClickListener(new OnClickListener(){

    @override
    public void onClick(View view)
    {
       openButton(view);
    }

});

0
投票

I had a related Question, so posted here.

这里如何在onCreate()第135行上传递带有以下arguments(164)的SavDb(View)方法。

© www.soinside.com 2019 - 2024. All rights reserved.