Android开发常见坑

1、初次定义Identifier时需要使用“+”号,而定义具体的资源时不需要。

2、资源的引用是由类型界定的,重名并不引起冲突。
3、用户界面上文本建议指定为字符串资源。详见官方文档
4、不会从活动代码引用的按钮不需要android:id属性。
5、为方便系统将指派给android:onClick方法匹配,方法签名必须如下:

  • 访问控制符为public
  • 返回值为void
  • 唯一的参数View,也就是待点击的视图

详见官方文档

6、源码中可以使用语法R.string.<string_name>引用字符串资源。如:

1
2
3
4
5
6
// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);

// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);

在XML文件中,可以使用@string/<string_name>引用字符串资源。如:

1
2
3
4
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

详见官方文档

7、使用android:drawable="@drawable/resource"为TextView添加图片,取代Image+TextView组合。

详见官方文档