如何在Eclipse中添加字符串资源?

Eri*_*k Z 16 eclipse string resources android

我可以让Eclipse添加我的字符​​串资源作为代码,还是我必须一直切换到string.xml并添加每个字符串?

JAL*_*JAL 25

Eclipse会为你做点什么.所以如果你有一个领域:

android:text="hello"
Run Code Online (Sandbox Code Playgroud)

选择"hello",然后转到Refactor - > Android - > Extract Android String,Eclipse会将行更改为:

android:text="@string/hello"
Run Code Online (Sandbox Code Playgroud)

并自动将该行添加到strings.xml中:

<string name="hello">Hello</string>
Run Code Online (Sandbox Code Playgroud)

JAL

  • 热键:ALT + SHIFT + A,S (5认同)
  • CTRL + 1更容易.看下面我的评论:) (5认同)

vog*_*Dev 8

Eclipse为此提供了极好的节省时间的快捷方式!

1.-在XML编辑器中:

假设您有一个Button,TextView或任何带有硬编码字符串的视图作为文本:

<Button    
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Text to add as string resource"/>
Run Code Online (Sandbox Code Playgroud)

将光标放在字符串文字上,按CTRL + 1,然后选择"提取Android字符串".选择所需的资源名称(例如my_string_resource),然后单击"确定".您将在strings.xml文件中获取字符串资源:

<string name="my_string_resource">Text to add as string resource</string>
Run Code Online (Sandbox Code Playgroud)

你的按钮现在看起来像:

<Button    
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/my_string_resource"/>
Run Code Online (Sandbox Code Playgroud)

全部自动且没有单一的上下文更改:)

2.-在代码编辑器中:

在代码中写一个字符串文字就像

mButton.setText("Text to add as String resource");
Run Code Online (Sandbox Code Playgroud)

然后选择字符串文字(从"到"),然后按CTRL + 1,将出现一个黄色菜单,双击"Extract Android String"(在这种情况下,S键对我不起作用,我只需双击选项).选择所需的名称(例如my_string_resouce),然后单击"确定".同样,您将获得一个新的strings.xml条目:

<string name="my_string_resource">Text to add as string resource</string>
Run Code Online (Sandbox Code Playgroud)

并将Button的setText行替换为:

mButton.setText(R.string.my_string_resource);
Run Code Online (Sandbox Code Playgroud)

希望它能帮助您,并为您节省尽可能多的时间!:)


Anj*_*nju 6

strings.xml内部values文件夹中最好的做法是保留所有字符串常量.因为如果你想进行任何改变,以后如果你保留在strings.xml中就很容易了.否则你将永远记住你写过该常量的文件.