歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android自定義控件實例

Android自定義控件實例

日期:2017/3/1 10:33:08   编辑:Linux編程

很多時候Android常用的控件不能滿足我們的需求,那麼我們就需要自定義一個控件了。今天做了一個自定義控件的實例,來分享下。

首先定義一個layout實現按鈕內部布局:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="horizontal" >
  6. <ImageView
  7. android:id="@+id/imageView1"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:layout_gravity="center_vertical"
  11. android:paddingBottom="5dip"
  12. android:paddingLeft="40dip"
  13. android:paddingTop="5dip"
  14. android:src="@drawable/right_icon" />
  15. <TextView
  16. android:id="@+id/textView1"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:layout_gravity="center_vertical"
  20. android:layout_marginLeft="8dip"
  21. android:text="確定"
  22. android:textColor="#000000" />
  23. </LinearLayout>

接下來寫一個類繼承LinearLayout,導入剛剛的布局,並且設置需要的方法,從而使的能在代碼中控制這個自定義控件內容的顯示。

  1. public class ImageBtn extends LinearLayout {
  2. private ImageView imageView;
  3. private TextView textView;
  4. public ImageBtn(Context context) {
  5. super(context);
  6. // TODO Auto-generated constructor stub
  7. }
  8. public ImageBtn(Context context, AttributeSet attrs) {
  9. super(context, attrs);
  10. // TODO Auto-generated constructor stub
  11. LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  12. inflater.inflate(R.layout.imagebtn, this);
  13. imageView=(ImageView) findViewById(R.id.imageView1);
  14. textView=(TextView)findViewById(R.id.textView1);
  15. }
  16. /**
  17. * 設置圖片資源
  18. */
  19. public void setImageResource(int resId) {
  20. imageView.setImageResource(resId);
  21. }
  22. /**
  23. * 設置顯示的文字
  24. */
  25. public void setTextViewText(String text) {
  26. textView.setText(text);
  27. }
  28. }
Copyright © Linux教程網 All Rights Reserved