日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android之在Layout中自定义View

發布時間:2025/6/15 Android 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android之在Layout中自定义View 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在Layout中自定義View

經常會看到在XML文件中調用別人的View就可以顯示出各種奇妙的頁面

簡單的學習了一下,下面說一下如何自定義一個View, 并設置背景色

  • // 第一步,創建一個繼承自View的類
  • public class MyView extends View {
  • // 背景顏色
  • private int background;
  • // 默認背景顏色
  • private final int default_background = Color.rgb(66, 145, 241);
  • // 構造
  • public MyView(Context context) {
  • // 這里確保每一級都會被觸發
  • this(context, null);
  • }
  • // 構造
  • public MyView(Context context, AttributeSet attrs) {
  • // 這里確保每一級都會被觸發
  • this(context, attrs, R.attr.MyViewStyle);
  • }
  • // 構造
  • public MyView(Context context, AttributeSet attrs, int defStyle) {
  • // 執行父類構造
  • super(context, attrs, defStyle);
  • // 初始化
  • final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0);
  • // 獲取設置的背景顏色
  • background = attributes.getColor(R.styleable.MyView_background, default_background);
  • // 設置
  • this.setBackgroundColor(background);
  • }
  • }

  • // 第二步,在XML-Layout中使用
  • <?xml version="1.0" encoding="utf-8"?>
  • <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  • xmlns:app="http://schemas.android.com/apk/res-auto"
  • android:layout_width="match_parent"
  • android:layout_height="match_parent"
  • android:background="@drawable/guide_0"
  • android:orientation="vertical">
  • // 這里使用的就是自定義的View
  • <com.example.nljb.surpass.MyView
  • // 可以使用自定義的View的設置參數
  • app:background="#ffff5633"
  • // 可以使用繼承自View的設置參數
  • android:layout_width="match_parent"
  • android:layout_height="50dp"/>
  • </RelativeLayout>

  • // 第三步,自定義View的參數(第一步已經講了如何使用)
  • // values/attrs
  • <?xml version="1.0" encoding="utf-8"?>
  • <resources>
  • <declare-styleable name="MyView">
  • // format 類型有很多 ...
  • <attr name="background" format="color"/>
  • // <attr name="..." format="integer"/>
  • // <attr name="..." format="dimension"/>
  • // <attr name="..." format="enum">
  • // <enum name="..." value="0"/>
  • // <enum name="..." value="1"/>
  • // </attr>
  • // <attr name="..." format="string"/>
  • // <attr name="..." format="boolean"/>
  • ...
  • </declare-styleable>
  • <declare-styleable name="Themes">
  • <attr name="MyViewStyle" format="reference"/>
  • </declare-styleable>
  • </resources>
  • 總結

    以上是生活随笔為你收集整理的Android之在Layout中自定义View的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。