【问题标题】:Android - Error if I don't import R and another error if I do?Android - 如果我不导入 R 会出错,如果我导入会出现另一个错误?
【发布时间】:2010-07-22 13:32:51
【问题描述】:

如果我不导入 R,我会得到“id 无法解析或不是字段”

(R.id.mainanim);

如果我导入 R,id 错误就消失了,但我得到“无法解析 main 和 mainanim 或者不是字段”。它们是我的 .xml 文件。

这是我的代码...也许有一个我没有看到的错误?

 package com.example.carrottest2;

 import android.app.Activity;
 import android.graphics.drawable.AnimationDrawable;
 import android.os.Bundle;
 import android.widget.ImageView;
 import android.R;

public class Carrottest2 extends Activity {
/** Called when the activity is first created. */

AnimationDrawable mainanimation; 

public void onCreate(Bundle icicle) {  
     super.onCreate(icicle);  
     setContentView(R.layout.main); 

     ImageView mainimage = (ImageView) findViewById(R.id.mainanim); 
     mainimage.setBackgroundResource(R.anim.mainanim); 
     mainanimation = (AnimationDrawable) mainimage.getBackground(); 

Main.XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>  
<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/hello"
/>
</LinearLayout>

Mainanim.xml:

<?xml version="1.0" encoding="UTF-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"     android:oneshot="false"> 
<item android:drawable="@drawable/carrotsmile" android:duration="2000" /> 
<item android:drawable="@drawable/carrotblink" android:duration="2000" /> 
</animation-list>    

【问题讨论】:

  • 删除:导入android.R;并在 Eclipse>Project 菜单中做一个干净的项目

标签: java android eclipse sdk


【解决方案1】:

Mainanim.xml 是一个布局,而不是一个 id。要在布局中制作动画,您需要一个 ImageView 来将 AnimationDrawable 设置为背景。

【讨论】:

  • ID 类似于 Main.xml 中的 TextView。它是 xml 文件中的一个对象。但是,为了“获取”id,您必须设置它,因此您在 xml 中的 TextView 将具有
【解决方案2】:

一般来说,当您遇到 R 问题时,您的 XML 布局文件之一有问题。 R 无法生成,因此在您的代码中对它的任何引用都会抛出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多