Vogella Android教程,Android Studio中的编译器错误

时间:2015-08-18 02:44:11

标签: java android

我是Android开发的新手,遵循Vogella使用Android Studio进行Android开发的简介 - 位于此处的教程:

http://www.vogella.com/tutorials/Android/article.html#androidstudio_starter

我在步骤19.4开始遇到问题。我有与教程中显示的完全相同的代码,但Android Studio在MainActivity.java中显示错误,指出它无法解析符号'常量'和编译失败,编译错误。我想知道我所缺少的内容,因为每个步骤都已被遵循,所有代码都与教程中列出的相匹配。

MainActivity.java

package com.deluxaur.testapp;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;


public class MainActivity extends Activity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (BuildConfig.DEBUG) {
        Log.d(Constants.LOG, "onCreated called");
    }
    setContentView(R.layout.activity_main);
}

public void onCLick(View view) {
    EditText input = (EditText) findViewById(R.id.main_input);
    String string = input.getText().toString();
    Toast.makeText(this, "Button 1 pressed", Toast.LENGTH_LONG).show();
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/main_input"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true"
    />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start"
    android:id="@+id/button"
    android:layout_alignLeft="@+id/main_input"
    android:layout_below="@+id/main_input"
    android:layout_marginTop="31dp"
    android:onClick="onClick"
    />

1 个答案:

答案 0 :(得分:2)

只是说Constants类不被识别。有很多方法可以解决这个问题。

  1. 您可以在其中创建带有静态LOG字符串变量的Constants类

    public class Constants {
        public static final String LOG = "MyLogTag";
    }
    
  2. 以下代码是可选的,您的程序功能不需要。它可以帮助您提供一些额外的日志,以便您更好地了解应用程序中发生的情况但不是必需的。

    //These three lines are optional
    if (BuildConfig.DEBUG) {
       Log.d(Constants.LOG, "onCreated called");
    }
    
  3. 或者您只需更改String键即可。 Log.d()方法需要两个String s,第一个用于标记,第二个用于消息。如果您只是提供另一个有效的String,它将正常工作。

    if (BuildConfig.DEBUG) {
       Log.d("A KEY", "onCreated called");
    }
    
相关问题