Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 ViewGroup 實作標籤流容器 FlowLayout 完整教學

編輯:關於 Android 程式設計

本文要談的是自訂 ViewGroup,實作一個標籤流式版面配置 FlowLayout。開發時我們經常需要「熱門標籤」這種會自動換行的流式版面,網路上這類 FlowLayout 很多,但不影響我對它的學習與研究。和往常一樣,主要還是藉此總結自訂 ViewGroup 的開發流程與幾個容易忽略的地方。

照慣例,先來看效果圖


一、動手前,先釐清幾個問題:

1、什麼是 ViewGroup:從字面看可譯為「檢視組」,顧名思義它內部包含了多個檢視,是一組 View。在 Android 的設計中,ViewGroup 也繼承自 View,這意味著 View 本身既可以是單一檢視,也可以是由多個檢視組成的一組。

2、ViewGroup 的種類:常見的有 LinearLayout、RelativeLayout、FrameLayout、AbsoluteLayout、GridLayout、TableLayout,其中 LinearLayout 與 RelativeLayout 最為常用。

3、ViewGroup 的職責:為 childView 計算建議的寬高與測量模式,然後決定 childView 的位置。

4、何謂流式版面(FlowLayout):就是讓子檢視依據 ViewGroup 的寬度自動由左至右排列,若當前這行放得下就放這行,放不下則自動換到下一行的最左側。

二、自訂 ViewGroup 的步驟:

1、自訂 ViewGroup 的屬性
2、在建構子中取得自訂屬性
3、覆寫 onMeasure
4、覆寫 onLayout

三、ViewGroup 的幾個建構子:

1、public FlowLayout(Context context):用 Java 程式碼直接 new 一個 FlowLayout 時會呼叫它。
2、public FlowLayout(Context context, AttributeSet attrs):在 XML 版面配置中建立時呼叫,AttributeSet 負責把 XML 中自訂的屬性帶進 View。
3、public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr):第三個參數是預設 Style,只有在明確呼叫時才會用到。
4、public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes):這個建構子是在 API 21 才加入的。

四、來看看自訂 ViewGroup 的主要程式碼

 1、自訂屬性:首先在 res/values/ 下建立 attr.xml,定義需要用到的屬性與取值類型

 <?xml version="1.0" encoding="utf-8"?> <resources> <!--每個item縱向間距--> <attr name="verticalSpacing" format="dimension" /> <!-- 每個item橫向間距--> <attr name="horizontalSpacing" format="dimension" /> <declare-styleable name="FlowLayout"> <attr name="verticalSpacing" /> <attr name="horizontalSpacing" /> </declare-styleable> </resources> 

我們定義了 verticalSpacing 與 horizontalSpacing 兩個屬性,分別代表標籤間的縱向與橫向間距,format 則是屬性取值類型,共有 string、color、dimension、integer、enum、reference、float、boolean、fraction 與 flag 等 10 種。

2、接著在 XML 版面配置中宣告自訂 View

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:custom="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="48dp" android:background="#38353D" android:gravity="center" android:text="標簽" android:textColor="@android:color/white" android:textSize="16dp" /> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tv_remind" android:layout_width="match_parent" android:layout_height="46dp" android:background="@android:color/white" android:gravity="center_vertical" android:paddingLeft="15dp" android:text="我的標簽(最多5個) " android:textSize="16dp" /> <com.per.flowlayoutdome.FlowLayout android:id="@+id/tcy_my_label" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:padding="5dp" android:visibility="gone" custom:horizontalSpacing="6dp" custom:verticalSpacing="12dp" /> <View android:layout_width="match_parent" android:layout_height="10dp" android:background="#f6f6f6" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="46dp" android:background="@android:color/white"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:paddingLeft="15dp" android:text="推薦標簽 " android:textSize="16dp" /> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#f6f6f6" /> <com.per.flowlayoutdome.FlowLayout android:id="@+id/tcy_hot_label" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/white" android:padding="5dp" custom:horizontalSpacing="6dp" custom:verticalSpacing="12dp" /> </LinearLayout> </ScrollView> </LinearLayout> 

記得引入 xmlns:custom="https://schemas.android.com/apk/res-auto",在 Android Studio 中可用 res-auto 命名空間,就不必再寫自訂 View 的完整類名。

3、在 View 的建構子中取得自訂樣式

 /** * 每個item縱向間距 */ private int mVerticalSpacing; /** * 每個item橫向間距 */ private int mHorizontalSpacing; public FlowLayout(Context context) { this(context, null); } public FlowLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FlowLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); /** * 獲得我們所定義的自定義樣式屬性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FlowLayout, defStyle, 0); for (int i = 0; i < a.getIndexCount(); i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.FlowLayout_verticalSpacing: mVerticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_verticalSpacing, 5); break; case R.styleable.FlowLayout_horizontalSpacing: mHorizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_horizontalSpacing, 10); break; } } a.recycle(); } 

我們覆寫了 3 個建構子,預設版面配置呼叫的是兩個參數的版本,因此要讓所有建構子最終都導向三個參數的版本,並在其中取得自訂屬性。原本一個與兩個參數的建構子寫法如下:

 public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } 

重點是把 super 改成 this,讓一個參數的建構子引用兩個參數的版本,兩個參數的版本再引用三個參數的版本:

 public FlowLayout(Context context) { this(context, null); } public FlowLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } 

4、覆寫 onMeasure 方法

 /** * 負責設置子控件的測量模式和大小 根據所有子控件設置自己的寬和高 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 獲得此ViewGroup上級容器為其推薦的寬和高,以及計算模式 */ int heighMode = MeasureSpec.getMode(heightMeasureSpec); int heighSize = MeasureSpec.getSize(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); /** * 高 */ int height = 0; /** * 每一行的高度,累加至height */ int lineHeight = 0; /** * 在warp_content情況下,記錄當前childView的左邊的一個位置 */ int childLeft = getPaddingLeft(); /** * 在warp_content情況下,記錄當前childView的上邊的一個位置 */ int childTop = getPaddingTop(); // getChildCount得到子view的數目,遍歷循環出每個子View for (int i = 0; i < getChildCount(); i++) { //拿到index上的子view View childView = getChildAt(i); // 測量每一個child的寬和高 measureChild(childView, widthMeasureSpec, heightMeasureSpec); //當前子空間實際占據的高度 int childHeight = childView.getMeasuredHeight(); //當前子空間實際占據的寬度 int childWidth = childView.getMeasuredWidth(); lineHeight = Math.max(childHeight, lineHeight);// 取最大值 //如果加入當前childView,超出最大寬度,則將目前最大寬度給width,類加height 然後開啟新行 if (childWidth + childLeft + getPaddingRight() > widthSize) { childLeft = getPaddingLeft();// 重新開啟新行,開始記錄childLeft childTop += mVerticalSpacing + childHeight;// 疊加當前的高度 lineHeight = childHeight;// 開啟記錄下一行的高度 }else{ //否則累加當前childView的寬度 childLeft += childWidth + mHorizontalSpacing; } } height += childTop + lineHeight + getPaddingBottom(); setMeasuredDimension(widthSize, heighMode == MeasureSpec.EXACTLY ? heighSize : height); } 

先取得父容器傳入的測量模式與寬高,再遍歷所有 childView 用 measureChild 測量,接著根據結果算出設為 wrap_content 時的高度;最後依模式判斷:若是 MeasureSpec.EXACTLY 就用父容器傳入的高度,否則用自己算出的高度。至於寬度,這裡預設為 MeasureSpec.EXACTLY。

5、覆寫 onLayout 方法

 @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int width = r - l; int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lineHeight = 0; //遍歷所有childView根據其寬和高,計算子控件應該出現的位置 for (int i = 0; i < getChildCount(); i++) { final View childView = getChildAt(i); if (childView.getVisibility() == View.GONE) { continue; } int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); lineHeight = Math.max(childHeight, lineHeight); // 如果已經需要換行 if (childLeft + childWidth + getPaddingRight() > width) { childLeft = getPaddingLeft(); childTop += mVerticalSpacing + lineHeight; lineHeight = childHeight; } childView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childLeft += childWidth + mHorizontalSpacing; } } 

onLayout 中完成對所有 childView 位置與大小的指定。

6、到此自訂 ViewGroup 的核心已完成,幾個重點:(1) getChildAt(int index) 取得 index 上的子 view;(2) getChildCount() 取得子 view 數目;(3) measureChild(childView, widthMeasureSpec, heightMeasureSpec) 測量每個 child 的寬高。

完成 FlowLayout 後,剩下就是一些邏輯程式碼。

五、邏輯程式碼

1、FlowLayout 完整程式碼:

 package com.per.flowlayoutdome; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** * @author: xiaolijuan * @description: 流式布局-標簽流容器 * @projectName: FlowLayoutDome * @date: 2016-06-16 * @time: 16:21 */ public class FlowLayout extends ViewGroup{ /** * 每個item縱向間距 */ private int mVerticalSpacing; /** * 每個item橫向間距 */ private int mHorizontalSpacing; private BaseAdapter mAdapter; private TagItemClickListener mListener; private DataChangeObserver mObserver; public FlowLayout(Context context) { this(context, null); } public FlowLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FlowLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); /** * 獲得我們所定義的自定義樣式屬性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FlowLayout, defStyle, 0); for (int i = 0; i < a.getIndexCount(); i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.FlowLayout_verticalSpacing: mVerticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_verticalSpacing, 5); break; case R.styleable.FlowLayout_horizontalSpacing: mHorizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_horizontalSpacing, 10); break; } } a.recycle(); } /** * 負責設置子控件的測量模式和大小 根據所有子控件設置自己的寬和高 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 獲得此ViewGroup上級容器為其推薦的寬和高,以及計算模式 */ int heighMode = MeasureSpec.getMode(heightMeasureSpec); int heighSize = MeasureSpec.getSize(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); /** * 高 */ int height = 0; /** * 每一行的高度,累加至height */ int lineHeight = 0; /** * 在warp_content情況下,記錄當前childView的左邊的一個位置 */ int childLeft = getPaddingLeft(); /** * 在warp_content情況下,記錄當前childView的上邊的一個位置 */ int childTop = getPaddingTop(); // getChildCount得到子view的數目,遍歷循環出每個子View for (int i = 0; i < getChildCount(); i++) { //拿到index上的子view View childView = getChildAt(i); // 測量每一個child的寬和高 measureChild(childView, widthMeasureSpec, heightMeasureSpec); //當前子空間實際占據的高度 int childHeight = childView.getMeasuredHeight(); //當前子空間實際占據的寬度 int childWidth = childView.getMeasuredWidth(); lineHeight = Math.max(childHeight, lineHeight);// 取最大值 //如果加入當前childView,超出最大寬度,則將目前最大寬度給width,類加height 然後開啟新行 if (childWidth + childLeft + getPaddingRight() > widthSize) { childLeft = getPaddingLeft();// 重新開啟新行,開始記錄childLeft childTop += mVerticalSpacing + childHeight;// 疊加當前的高度 lineHeight = childHeight;// 開啟記錄下一行的高度 }else{ //否則累加當前childView的寬度 childLeft += childWidth + mHorizontalSpacing; } } height += childTop + lineHeight + getPaddingBottom(); setMeasuredDimension(widthSize, heighMode == MeasureSpec.EXACTLY ? heighSize : height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int width = r - l; int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); int lineHeight = 0; //遍歷所有childView根據其寬和高,計算子控件應該出現的位置 for (int i = 0; i < getChildCount(); i++) { final View childView = getChildAt(i); if (childView.getVisibility() == View.GONE) { continue; } int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); lineHeight = Math.max(childHeight, lineHeight); // 如果已經需要換行 if (childLeft + childWidth + getPaddingRight() > width) { childLeft = getPaddingLeft(); childTop += mVerticalSpacing + lineHeight; lineHeight = childHeight; } childView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); childLeft += childWidth + mHorizontalSpacing; } } private void drawLayout() { if (mAdapter == null || mAdapter.getCount() == 0) { return; } removeAllViews(); for (int i = 0; i < mAdapter.getCount(); i++) { View view = mAdapter.getView(i, null, null); final int position = i; view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.itemClick(position); } } }); addView(view); } } public void setAdapter(BaseAdapter adapter) { if (mAdapter == null) { mAdapter = adapter; if (mObserver == null) { mObserver = new DataChangeObserver(); mAdapter.registerDataSetObserver(mObserver); } drawLayout(); } } public void setItemClickListener(TagItemClickListener mListener) { this.mListener = mListener; } public interface TagItemClickListener { void itemClick(int position); } class DataChangeObserver extends DataSetObserver { @Override public void onChanged() { drawLayout(); } @Override public void onInvalidated() { super.onInvalidated(); } } } 

2、FlowLayoutAdapter

 package com.per.flowlayoutdome; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import java.util.List; /** * @author: adan * @description: 流式布局適配器 * @projectName: FlowLayoutDome * @date: 2016-06-16 * @time: 16:22 */ public class FlowLayoutAdapter extends BaseAdapter { private Context mContext; private List<String> mList; public FlowLayoutAdapter(Context context, List<String> list) { mContext = context; mList = list; } @Override public int getCount() { return mList.size(); } @Override public String getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.item_tag, null); holder = new ViewHolder(); holder.mBtnTag = (Button) convertView.findViewById(R.id.btn_tag); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.mBtnTag.setText(getItem(position)); return convertView; } static class ViewHolder { Button mBtnTag; } } 

3、MainActivity

 package com.per.flowlayoutdome; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { private TextView tv_remind; private FlowLayout tcy_my_label, tcy_hot_label; private FlowLayoutAdapter mMyLabelAdapter, mHotLabelAdapter; private List<String> MyLabelLists, HotLabelLists; private static int TAG_REQUESTCODE = 0x101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); } private void initView() { tv_remind = (TextView) findViewById(R.id.tv_remind); tcy_my_label = (FlowLayout) findViewById(R.id.tcy_my_label); tcy_hot_label = (FlowLayout) findViewById(R.id.tcy_hot_label); } private void initData() { String[] date = getResources().getStringArray(R.array.tags); HotLabelLists = new ArrayList<>(); for (int i = 0; i < date.length; i++) { HotLabelLists.add(date[i]); } mHotLabelAdapter = new FlowLayoutAdapter(this, HotLabelLists); tcy_hot_label.setAdapter(mHotLabelAdapter); tcy_hot_label.setItemClickListener(new TagCloudLayoutItemOnClick(1)); MyLabelLists = new ArrayList<>(); mMyLabelAdapter = new FlowLayoutAdapter(this, MyLabelLists); tcy_my_label.setAdapter(mMyLabelAdapter); tcy_my_label.setItemClickListener(new TagCloudLayoutItemOnClick(0)); String labels = String.valueOf(getIntent().getStringExtra("labels")); if (!TextUtils.isEmpty(labels) && labels.length() > 0 && !labels.equals("null")) { String[] temp = labels.split(","); for (int i = 0; i < temp.length; i++) { MyLabelLists.add(temp[i]); } ChangeMyLabels(); } } /** * 刷新我的標簽數據 */ private void ChangeMyLabels() { tv_remind.setVisibility(MyLabelLists.size() > 0 ? View.GONE : View.VISIBLE); tcy_my_label.setVisibility(MyLabelLists.size() > 0 ? View.VISIBLE : View.GONE); mMyLabelAdapter.notifyDataSetChanged(); } /** * 標簽的點擊事件 * * @author lijuan */ class TagCloudLayoutItemOnClick implements FlowLayout.TagItemClickListener { int index; public TagCloudLayoutItemOnClick(int index) { this.index = index; } @Override public void itemClick(int position) { switch (index) { case 0: MyLabelLists.remove(MyLabelLists.get(position)); ChangeMyLabels(); break; case 1: if (MyLabelLists.size() < 5) { if (HotLabelLists.get(position).equals("自定義")) { startActivityForResult( new Intent(MainActivity.this, AddTagActivity.class), TAG_REQUESTCODE); } else { Boolean isExits = isExist(MyLabelLists, HotLabelLists.get(position)); if (isExits) { Toast.makeText(MainActivity.this, "此標簽已經添加啦", Toast.LENGTH_LONG).show(); return; } MyLabelLists.add(HotLabelLists.get(position)); ChangeMyLabels(); } } else { Toast.makeText(MainActivity.this, "最多只能添加5個標簽", Toast.LENGTH_LONG).show(); } break; default: break; } } } /** * 將數組裡面的字符串遍歷一遍,看是否存在相同標簽 * * @param str * @param compareStr * @return */ public static Boolean isExist(List<String> str, String compareStr) { Boolean isExist = false;//默認沒有相同標簽 for (int i = 0; i < str.size(); i++) { if (compareStr.equals(str.get(i))) { isExist = true; } } return isExist; } /** * 回傳數據 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (TAG_REQUESTCODE == requestCode) { if (resultCode == AddTagActivity.TAG_RESULTCODE) { String label = data.getStringExtra("tags"); MyLabelLists.add(label); ChangeMyLabels(); } } } } 

4、AddTagActivity

 package com.per.flowlayoutdome; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * @author: xiaolijuan * @description: 添加自定義標簽 * @date: 2016-06-10 * @time: 14:37 */ public class AddTagActivity extends Activity implements View.OnClickListener{ private EditText mEtLabel; private Button mBtnSure; public final static int TAG_RESULTCODE = 0x102; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_tag); initView(); initData(); } private void initData() { // 根據輸入框輸入值的改變提示最大允許輸入的個數 mEtLabel.addTextChangedListener(new TextWatcher_Enum()); } private void initView() { mEtLabel = (EditText) findViewById(R.id.et_label); mBtnSure = (Button) findViewById(R.id.btn_sure); mBtnSure.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_sure: String label = mEtLabel.getText().toString(); if (TextUtils.isEmpty(label)) { Toast.makeText(AddTagActivity.this,"自定義標簽不應為空",Toast.LENGTH_LONG).show(); return; } Intent intent = getIntent(); intent.putExtra("tags", label); setResult(TAG_RESULTCODE, intent); finish(); break; } } /** * 根據輸入框輸入值的長度超過8個字符的時候,彈出輸入的標簽應控制在8個字 * * @author lijuan * */ class TextWatcher_Enum implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { int lenght = mEtLabel.getText().toString().trim().length(); if (lenght > 8) { Toast.makeText(AddTagActivity.this,"輸入的標簽應控制在8個字",Toast.LENGTH_LONG).show(); } } @Override public void afterTextChanged(Editable s) { } } } 

5、activity_main.xml 前面已貼出,這裡不重複;我們另外建立 arrays.xml,定義一些熱門標籤:

 <?xml version="1.0" encoding="UTF-8"?> <resources> <string-array name="tags"> <item>美妝</item> <item>畫板</item> <item>漫畫</item> <item>高科技</item> <item>韓國電影</item> <item>股票</item> <item>美術</item> <item>高富帥</item> <item>鴻泰安</item> <item>運動</item> <item>外語</item> <item>財經</item> <item>大叔</item> <item>非主流</item> <item>暴走漫畫</item> <item>心理學</item> <item>漢語</item> <item>白富美</item> <item>自定義</item> </string-array> </resources> 

6、item_tag.xml

 <?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/btn_tag" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/selector_btn_item" android:gravity="center" android:minHeight="30dp" android:minWidth="45dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:textSize="12sp" /> 

6、activity_add_tag.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="250dp" android:layout_height="wrap_content" android:background="@android:color/white" android:gravity="center_horizontal" android:orientation="vertical" android:padding="5dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:text="請輸入想要添加的標簽" android:textColor="@android:color/black" android:textSize="16dp" /> <EditText android:id="@+id/et_label" android:layout_width="match_parent" android:layout_height="80dp" android:layout_margin="5dp" android:background="@drawable/selector_btn_item" android:gravity="center_vertical|start" android:maxLength="8" android:paddingLeft="10dp" android:textColor="@android:color/black" android:textSize="16dp" /> </LinearLayout> <Button android:id="@+id/btn_sure" android:layout_width="50dp" android:layout_height="32dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="5dp" android:background="#38353D" android:gravity="center" android:text="確定" android:textColor="@android:color/white" android:textSize="14dp" /> </LinearLayout> 

7、selector_btn_item.xml

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape> <solid android:color="#ff76787b" /> <corners android:bottomLeftRadius="5dp" android:bottomRightRadius="5dp" android:topLeftRadius="5dp" android:topRightRadius="5dp" /> <stroke android:width="1px" android:color="#ffd1d1d1" /> </shape> </item> <item> <shape> <solid android:color="#ffffff" /> <corners android:bottomLeftRadius="2.5dp" android:bottomRightRadius="2.5dp" android:topLeftRadius="2.5dp" android:topRightRadius="2.5dp" /> <stroke android:width="0.5px" android:color="#ffd1d1d1" /> </shape> </item> </selector> 

最後一步,在 AndroidManifest.xml 中加入

 <activity android:name=".AddTagActivity" android:theme="@style/dialogstyle" /> 

用於讓自訂標籤頁以類似對話框的形式彈出,這裡引用了自訂樣式

 <style name="dialogstyle"> <!--設置dialog的背景--> <item name="android:windowBackground">@android:color/transparent</item> <!--設置Dialog的windowFrame框為無--> <item name="android:windowFrame">@null</item> <!--設置無標題--> <item name="android:windowNoTitle">true</item> <!--是否浮現在activity之上--> <item name="android:windowIsFloating">true</item> <!--是否半透明--> <item name="android:windowIsTranslucent">true</item> <!--設置窗口內容不覆蓋--> <item name="android:windowContentOverlay">@null</item> <!--設置動畫,在這裡使用讓它繼承系統的Animation.Dialog--> <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item> <!--背景是否模糊顯示--> <item name="android:backgroundDimEnabled">true</item> </style> 

關於這個類似對話框的 Activity,若有不清楚的地方,可以參考我之前的文章:Android 中使用 Dialog 風格彈出框的 Activity。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved