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

動態載入 XML 與控制項,打造 QQ 好友印象功能

編輯:關於 Android 程式設計

在 Android 開發中,我們常遇到「版面控制項數量無法事先確定」的情況。無論是基於功能需求,還是為了凸顯 App 特色,有時需要動態去載入控制項。本文就以「動態載入控制項」為切入點,模擬實作 QQ 的好友印象功能,同時示範如何動態載入一份 XML 設定檔。

要完成好友印象,大致可分為三個步驟:

1. 介面一開始載入一個 EditText 與一個 Button,分別用來輸入印象內容與新增印象;

2. 新建一份 arrays.xml,在其中定義印象標籤的背景顏色;

3. 在 Activity 中載入這份 XML,取出顏色,並為 Button 掛上事件監聽,點擊後自動產生帶有背景顏色的印象標籤。

先在設定檔中隨意定義幾種顏色:

arrays.xml
   #ff78ff #abcd12 #cdba34 #345677  

接著看如何載入設定檔與控制項:

package com.example.sundyandroidtest; import java.util.Random; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; public class AutoColorShowActivity extends Activity{ String[] aColors; LinearLayout mLayout = null; LinearLayout.LayoutParams lpFF; LinearLayout.LayoutParams lpWW; TextView colorTextView = null; Button butAdd = null; EditText editText = null; Random rand = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); aColors = getResources().getStringArray(R.array.colorsArray); mLayout = new LinearLayout(this); mLayout.setOrientation(LinearLayout.VERTICAL); lpFF = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); lpWW = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); mLayout.setLayoutParams(lpFF); editText = new EditText(this); mLayout.addView(editText, lpWW); butAdd = new Button(this); butAdd.setText("添加"); mLayout.addView(butAdd, lpWW); setContentView(mLayout); rand = new Random(); butAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int tag = rand.nextInt(aColors.length-1); String info = editText.getText().toString(); colorTextView = new TextView(AutoColorShowActivity.this); colorTextView.setText(info); colorTextView.setTextColor(Color.BLACK); colorTextView.setTextSize(30f); colorTextView.setBackgroundColor(Color.parseColor(aColors[tag])); mLayout.addView(colorTextView, lpWW); editText.setText(""); mLayout.refreshDrawableState(); } }); } }

透過 Random 隨機挑選顏色,再配合動態 addView,就能讓每次點擊都產生不同色塊的印象標籤,整個流程相當直觀。

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