編輯:關於 Android 程式設計
本文示範第二種實作方式,也是我個人最推薦的一種。做法是先建立一個「圖片+文字」的 XML 版面配置,再撰寫一個繼承自 LinearLayout 的類別,最後在程式中實例化並設定參數。
版面配置使用垂直排列的 LinearLayout,內含一個 ImageView 與一個 TextView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#87CE..."
android:orientation="vertical">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="5dip"
android:paddingTop="5dip" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF6100"
android:textSize="30dip"
android:layout_gravity="center_vertical"/>
</LinearLayout>
這個類別繼承 LinearLayout,並在 Constructor 中透過 LayoutInflater 載入版面配置,再對外提供設定圖片、文字與字級的介面:
package yan.guoqi.testimgbtn;
public class MyImgBtn extends LinearLayout {
private ImageView mImgView = null;
private TextView mTextView = null;
private Context mContext;
public MyImgBtn(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.myimgbtn_layout, this, true);
mContext = context;
mImgView = (ImageView) findViewById(R.id.img);
mTextView = (TextView) findViewById(R.id.text);
}
/* 設定圖片介面 */
public void setImageResource(int resId){ mImgView.setImageResource(resId); }
/* 設定文字介面 */
public void setText(String str){ mTextView.setText(str); }
/* 設定文字大小 */
public void setTextSize(float size){ mTextView.setTextSize(size); }
}
在 main.xml 中,直接用完整類別路徑當作標籤,將自訂控制項嵌入版面:
<yan.guoqi.testimgbtn.MyImgBtn
android:id="@+id/MyIBtn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true" />
在 Activity 中取得控制項實例,設定圖片、文字與字級,並掛上點擊事件:
MyIBtn1 = (MyImgBtn) findViewById(R.id.MyIBtn_1);
MyIBtn1.setImageResource(R.drawable.ic_launcher);
MyIBtn1.setText("歡迎光臨");
MyIBtn1.setTextSize(24.0f);
MyIBtn1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(TestImgBtnActivity.this, "您好", Toast.LENGTH_SHORT).show();
}
});
這種做法直觀又容易理解,相比第一種使用 Gallery 的方式,不必去適應 Gallery 相關的 Adapter 配置,對初學者更友善。它特別適合背景為純色、內含「圖片+文字」的情境,例如 360 手機安全衛士的主視窗。美中不足的是,若想加上按下時背景變色的效果,還需要補上 OnTouchListener 的實作。
Android 自訂特效:用 Canvas 與插值器實作水波紋擴散
水波紋特效大家應該都不陌生,印象中大略有幾種類型:支付類 App 的「咻咻咻」擴散圈、流量監控那種球體的「蕩漾」感,以及真正模擬物理水波、需要處理 Bitmap 的寫實版
Android AutoCompleteTextView 自動提示文本框實例詳解
自動提示文本框(AutoCompleteTextView)能夠顯著提升用戶體驗,縮短輸入耗時,百度搜索框的即時提示就是最典型的例子。先展示效果圖,如果覺得還不錯,不妨參考
Android 學習筆記:Fragment 之間如何交互
在一個 Activity 中,往往會同時包含多個 Fragment。它們各自負責不同的界面區域,但需要協同工作,才能呈現完整的用戶體驗。因此,Fragment 之間的通信
ListView 懸浮頭部效果實作教學
在許多個人中心或資料列表頁面中,常會看到某個區塊在滑動到頂部後固定顯示,不再隨列表滾動離開畫面。這種效果可以透過 ListView 的 HeaderView 與覆蓋層搭配