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

自訂「圖片+文字」控制項的四種做法之二:我最推薦的 LinearLayout 繼承法

編輯:關於 Android 程式設計

本文示範第二種實作方式,也是我個人最推薦的一種。做法是先建立一個「圖片+文字」的 XML 版面配置,再撰寫一個繼承自 LinearLayout 的類別,最後在程式中實例化並設定參數。

第一部分:myimgbtn_layout.xml

版面配置使用垂直排列的 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>

第二部分:對應的 MyImgBtn.java

這個類別繼承 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

在 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 的實作。

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