首页 > 解决方案 > 如何在 Activity 类中实现方法

问题描述

我刚刚开始使用 Android Studio 学习 Android 编程,不幸的是,我遇到了一个可能非常简单的问题,即在主活动的布局文件中,我将 startActivity() 方法分配给android:onClick了两个按钮(android:onClick="startActivity()")。

现在我应该在 MainActivity 类中实现 startActivity() 方法,但是....我不知道该怎么做。
我看到我应该在 MainActivity: public void startActivity(View v)。我尝试了几个小时,一直在寻找解决方案,但我已经失去了希望。
特别是我可以实现例如 View.OnClickListener 但方法 startActivity() 不能再做。我怎么能实现这个方法?

我将 startActivity() 方法分配给 activity_main.xml 中两个按钮的 android:onClick 属性:

<Button
    android:id="@+id/button"
    android:onClick="startActivity()"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="24dp"
    android:text="@string/button"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:ignore="OnClick" />

<Button
    android:id="@+id/button2"
    android:onClick="startActivity()"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="16dp"
    android:text="@string/button2"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button"
    tools:ignore="OnClick" />

接下来我应该在 MainActivity 类中,实现 startActivity() 方法但是....我不知道该怎么做:

public class MainActivity extends AppCompatActivity implements startActivity() {



    Button  b1, b2;
    EditText et1, et2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        b1 = findViewById(R.id.button);
        b2 = findViewById(R.id.button2);
        et1 = findViewById(R.id.editText);
        et2 = findViewById(R.id.editText2);


        public void startActivity(View v) {
            if (v.getId() == R.id.button) {
                String name = et1.getText().toString();
                int age = Integer.parseInt(et2.getText().toString());
                Intent i = new Intent(this, ResultActivity.class);
                i.putExtra("name", name);
                i.putExtra("age", age);
                startActivity(i);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW,
        Uri.parse("http://www.google.pl/"));
                startActivity(i);     }

    }

}

标签: javaandroid

解决方案


您错误地使用了onClick属性。这是错误的:

android:onClick="startActivity()"

它应该是:

android:onClick="startActivity"

阅读更多https://developer.android.com/guide/topics/ui/controls/button#HandlingEvents


建议
您应该避免android:onClick在您的 xml 中使用。改为使用onClickListener。将你的逻辑和 UI 布局分开很重要,这样每当你的 xml 布局发生变化时,你就不需要考虑太多。使用这样的东西:

Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Do something here when button is clicked.
    }
});

推荐阅读