Dal*_*kar 6 android android-layout android-studio
当Android资源ID不属于在Activity中膨胀的布局时,有没有办法显示一些警告/错误?
下面是一个简单的例子,但在更复杂的布局中,追踪这些问题要困难得多,因为它们只能在运行时找到.我希望能够在编译时捕获它们.
MainActivity初始化
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// how to prevent erroneous usage of R.id.text2 at compile time
TextView t = (TextView) findViewById(R.id.text2);
}
Run Code Online (Sandbox Code Playgroud)
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"
tools:context=".MainActivity">
<TextView android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
activity_second.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"
tools:context=".SecondActivity">
<TextView android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
我不知道有任何 Lint 检查或类似的检查可以满足您的要求。我会提出一个功能请求,因为它看起来是一个有用的功能。
目前我将在标识符中使用前缀。例如:
findViewById(act_main_text1);
findViewById(act_main_text2);
root.findViewById(fragment_preferences_username);
Run Code Online (Sandbox Code Playgroud)
等等。它不会在构建阶段引发错误/警告,但它会让您的生活更轻松,因为您将始终知道该特定 id 属于哪个活动/片段/视图。
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |