程序工作正常但是eclipse正在显示textview的警告

时间:2013-07-15 21:20:54

标签: android

我想知道为什么eclipse在下面的xml代码中显示警告“[I18N]硬编码字符串”TextView“,应该使用@string资源”。实际上我试图在编辑文本中获取用户编写的文本在当前活动的活动中。

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="0.01"
            android:text="TextView" />

    </LinearLayout>

3 个答案:

答案 0 :(得分:2)

您收到警告的原因是,由于可能存在冗余,您正在尝试对Android编程中不太合理的字符串进行硬编码:

    <TextView
        ...
        android:text="TextView" />

您应该在... / res / values / strings.xml文件中创建对字符串的引用,如下所示:

    <TextView
        ...
        android:text="@string/TextView" />

..并在strings.xml文件中定义它:

<string name="TextView">TextView</string>

希望这有帮助。

答案 1 :(得分:0)

如上所述,您使用的是“硬编码”字符串,其效率低于使用String resource。只需删除

android:text="TextView"

如果您不希望显示警告。如果你想要它,那么忽略警告或将其添加到String resource文件。不需要Text属性。如果您希望用户输入,则应将其更改为EditText,除非您有理由使用TextView

<EditText
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.01" />

然后,如果您希望它在View中显示诸如“在此输入输入”之类的内容,则可以添加android:hint"Text to display"。但如果您不将其添加到strings.xml并使用android:hint="@string/nameInStringsFile",则会向您发出相同的警告。

但这些警告就是这样。建议可能更有效的方法或实现你正在做的事情的方法。

答案 2 :(得分:0)

将XML更改为以下内容以删除警告

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="0.01" />

    </LinearLayout>

您看到警告的原因是您在XML布局文件中将文本设置为“TextView”。将所有字符串放在您创建string resources的res / values文件夹中的strings.xml文件中是Android的最佳做法。您在资源文件中有一个字符串,您可以使用语法“@ string / string_name”从布局文件中引用它。