- 在安卓開發控件的百分比布局學習中,由於我參考的是第一行代碼中的資源,其中的Android studio版本過低,導致的一些錯誤,花了好長時間來解決它。這里我用的是Android studio 3.5.3
首先是依賴的添加,由於我使用的版本相比參考書中的高,Android studio中已經不支持在compile,所以我在模塊級build.gradle添加如下的依賴:
1 implementation 'androidx.percentlayout:percentlayout:1.0.0'
1 dependencies { 2 implementation 'androidx.percentlayout:percentlayout:1.0.0' 3 implementation fileTree(dir: 'libs', include: ['*.jar']) 4 implementation 'androidx.appcompat:appcompat:1.1.0' 5 implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 6 testImplementation 'junit:junit:4.12' 7 androidTestImplementation 'androidx.test.ext:junit:1.1.0' 8 androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 9 }
后面就是對layout中的 *.xml 文件進行修改,這里的話百分比布局中分 PercentRelativeLayout 和 PercentFrameLayout 兩種我采用的是PercentRelativeLayout,代碼如下
1 <androidx.percentlayout.widget.PercentRelativeLayout 2 xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent"> 6 7 <TextView 8 android:id="@+id/row_one_item_one" 9 android:layout_width="0dp" 10 android:layout_height="0dp" 11 android:layout_alignParentTop="true" 12 android:background="#7700ff00" 13 android:text="w:70%,h:20%" 14 android:gravity="center" 15 app:layout_heightPercent="20%" 16 app:layout_widthPercent="70%"/> 17 18 <TextView 19 android:id="@+id/row_one_item_two" 20 android:layout_width="0dp" 21 android:layout_height="0dp" 22 android:layout_toRightOf="@+id/row_one_item_one" 23 android:background="#396190" 24 android:text="w:30%,h:20%" 25 app:layout_heightPercent="20%" 26 android:gravity="center" 27 app:layout_widthPercent="30%"/> 28 29 30 <ImageView 31 android:id="@+id/row_two_item_one" 32 android:layout_width="match_parent" 33 android:layout_height="0dp" 34 android:src="@drawable/img_1" 35 android:scaleType="centerCrop" 36 android:layout_below="@+id/row_one_item_one" 37 android:background="#d89695" 38 app:layout_heightPercent="70%"/> 39 40 <TextView 41 android:layout_width="0dp" 42 android:layout_height="0dp" 43 android:layout_below="@id/row_two_item_one" 44 android:background="#770000ff" 45 android:gravity="center" 46 android:text="width:100%,height:10%" 47 app:layout_heightPercent="10%" 48 app:layout_widthPercent="100%"/> 49 50 51 </androidx.percentlayout.widget.PercentRelativeLayout>
這里我參照了一位博友的博客
http://blog.csdn.net/lmj623565791/article/details/46695347;
想了解其中的源碼分析可以參考這個博客。