如何解决 Android Studio 中的重新声明错误

Jam*_*ame 5 java android kotlin

此代码用于 android 模拟器上的按钮。但是,当我将此代码放在主 activity.kt 中时,它给了我多个错误。我遇到的第一个错误是主活动第 9 行的重新声明错误

package com.example.android.justjava

import android.R
import android.os.Bundle
import android.support.v7.app.ActionBarActivity
import android.view.View
import android.widget.TextView

// This activity displays an order form to order coffee.
class MainActivity : ActionBarActivity() {
    protected fun onCreate(savedInstanceState: Bundle) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
    }

    // this method is called when the order button is clicked.
    fun submitOrder(view: View) {
      display(1)
    }

    // This method displays the given quantity value on the screen.
    private fun display(number: Int) {
      val quantityTextView = findViewById(R.id.quantity_text_view as TextView
      quantityTextView.text = "" + number
    }
}
Run Code Online (Sandbox Code Playgroud)

此活动显示订购咖啡的订单。

public class MainActivity extends ActionBarActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   // This method is called when the order button is clicked.
   public void submitOrder(View view) {
       display(1);
   }

   // This method displays the given quantity value on the screen.
   private void display(int number) {
      TextView quantityTextView =(TextView) findViewById (R.id.quantity_text_view);
      quantityTextView.setText("" + number);
   }
}
Run Code Online (Sandbox Code Playgroud)

Arm*_*ght 9

  1. 文件选项卡 -> 使缓存无效/重新启动(然后从将出现的对话框中选择无效并重新启动)
  2. 构建选项卡 -> 清理项目 3.构建选项卡 -> 重建

这应该可以解决问题。这个解决方案与@Ehsan_Haghdoust 解决方案相同,但让 Android Studio 为我做这件事,而不是我自己做。


elc*_*uco 0

您面临的问题是您有 2 个同名活动MainActivity- 一个在 Java 中,第二个在 Koltin 中。两个类(在本例中为活动)都被编译到同一个应用程序中 - 您有 2 个具有相同名称的符号。

是的,编译器完成处理后,Koltin 和 Java 看起来是一样的:)