简体   繁体   English

Android Studio - 按钮 onClick() 不工作

[英]Android Studio - Button onClick() is not working

I have two buttons on my main Activity, which both should lead to another activity, but when I run the code it is showing an error.我的主 Activity 上有两个按钮,它们都应该导致另一个活动,但是当我运行代码时它显示错误。

MainActivity.java is this: MainActivity.java 是这样的:

package com.assignment2.courier;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void second (View v){
        Intent i = new Intent(this, adelivery.class);
        startActivity(i);

    }
    }
}

This is the button code in activity_main.xml这是activity_main.xml中的按钮代码

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="85dp"
        android:layout_marginBottom="234dp"
        android:onClick="second"
        android:text="Arrange Delivery"
        android:textSize="20sp" />

Error: Failed to compile values file错误:无法编译值文件

What is the problem here?这里有什么问题?

The problem here is that the second function is inside the onCreate这里的问题是second function 在onCreate里面

You need to adapt the code as follows:您需要按如下方式调整代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void second (View v){
    Intent i = new Intent(this, adelivery.class);
    startActivity(i);

  }
}

You should move second method out of the onCreate method;您应该将第二种方法移出 onCreate 方法; this is the problem in your code.这是您的代码中的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM