Android自定義View簡單實現流式動態添加圓角矩形氣泡

Android自定義View簡單實現流式動態添加圓角矩形氣泡

簡單學習玩轉自定義View

1.首先在如圖

在該包中新建一個包,在包中創建一個類

在這裏插入圖片描述

因該效果爲容器,需繼承ViewGroup(非容器繼承View)實現三個構造,一個佈局方法在這裏插入圖片描述

之後在該MainActivity的xml佈局中創建一個輸入框一個TextView設置點擊事件,及上面的類引用創建的一個控件,設置Id

在這裏插入圖片描述

實現點擊事件在MainActivity中實現添加子控件方法,找控件,然後在實現的方法裏創建一個引用類中的方法,傳入獲取輸入框中的值,創建該方法

在這裏插入圖片描述

在drawable中新建一個xml如下圖

在這裏插入圖片描述
在這裏插入圖片描述

在xml中做如下操作

在這裏插入圖片描述

在添加子控件方法中動態創建TextView

在這裏插入圖片描述

在該類中的佈局方法中,先將左上右下賦值爲0

protected void onLayout(boolean changed, int l, int t, int r, int b) {
int left=0;
int top=0;
int right=0;
int bottom=0;
//獲取子類數量
int childCount = getChildCount();
//判斷子類數量是否大於0
if (childCount>0){
for (int i = 0; i < childCount; i++) {
//獲取每個子控件
View childView = getChildAt(i);
//自動測量
childView.measure(0,0);
//獲取測量寬高
int measuredWidth = childView.getMeasuredWidth();
int measuredHeight = childView.getMeasuredHeight();
//獲取控件右邊的位置
right=left+measuredWidth;
//判斷是否大於屏幕寬度,
if (right>getWidth()){//如果大於換行
left=0;
right=left+measuredWidth;
top=bottom+10;
}
//不換行
bottom=top+measuredHeight;
//子控件佈局左右頂底
childView.layout(left,top,right,bottom);
//左側距離累加
left+=measuredWidth+10;
//結束
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章