有時候調試別人寫的代碼或者是android源碼的時候,不知道當前界面的代碼位置,那我們如何定位呢?以下,以SnapdragonCamera爲例,定位拍照按鈕的點擊實現。首先我們將設備連接電腦,打開camera如下圖:
打開Android Studio,打開ADM
打開之後,選擇HierarchyViewer 選項
由上圖可知,當前界面所在的Activity爲CameraLauncher,打開AndroidManifest,找到CameraLauncher的定義
<activity-alias
android:name="com.android.camera.CameraLauncher"
android:icon="@mipmap/ic_launcher_camera"
android:label="@string/snapcam_app_name"
android:launchMode="singleTop"
android:targetActivity="com.android.camera.CameraActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
原來CameraLauncher只是CameraActivity的別名,真正的主頁面是CameraActivity這個類,我們打開這個類,找到它的佈局文件。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/camera_root_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.android.camera.ui.CameraRootView
android:id="@+id/camera_photo_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.android.camera.ui.CameraRootView>
<com.android.camera.ui.CameraRootView
android:id="@+id/camera_video_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.android.camera.ui.CameraRootView>
<com.android.camera.ui.CameraRootView
android:id="@+id/camera_pano_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.android.camera.ui.CameraRootView>
<com.android.camera.ui.CameraRootView
android:id="@+id/camera_capture_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.android.camera.ui.CameraRootView>
</FrameLayout>
佈局文件非常簡單,看來camera的UI做了層層封裝,通過此方法無法快速定位拍照按鈕的位置,我們來看第二種方式:用UI Automator Viewer 來定位,同樣打開ADM,選擇DDMS,保持相機處於預覽界面,操作如下
通過Ctrl+H全局搜索,查詢id/shutter_button 如下,找到拍照按鈕的佈局代碼
查看佈局文件,按鈕的佈局爲
<com.android.camera.ShutterButton
android:id="@+id/shutter_button"
android:layout_width="@dimen/shutter_size"
android:layout_height="@dimen/shutter_size"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginBottom="@dimen/shutter_offset"
android:clickable="true"
android:contentDescription="@string/accessibility_shutter_button"
android:focusable="true"
android:scaleType="fitCenter"
android:src="@drawable/btn_new_shutter" />
是一個自定義的Button控件,其點擊事件實現在 ShutterButton內部
@Override
public boolean performClick() {
boolean result = super.performClick();
if (mListener != null && getVisibility() == View.VISIBLE) {
mListener.onShutterButtonClick();
}
return result;
}
全局搜索shutter_button我們可以得知,當前佈局被封裝在CaptureUI 、 VideoUI 、PhotoUI中。