Android開發自定義控件全解

Android開發自定義控件全解,安卓自定義控件:包含LinearLayout、RelativeLayout、GridView、Button等。

本文以LinearLayout為例

首先要有一個自定義xml佈局文件

我們這裡存儲下面的代碼為ui_linearlayout.xml文件



  

自定義控件繼承自LinearLayout

在自定義控件的綁定佈局文件,並進行相應的ui初始化,添加自定義的屬性和方法。

//自定義組合控件
public class UI_LinearLayout extends LinearLayout{  
      private View view;
      private LayoutInflater layoutInflater;
      private EditText editText;
      private Button clearButton;

      public UI_LinearLayout(Context context) {   //自己定義構造函數,可以傳遞想要的數據進來
        super(context);

        //使用佈局資源填充視圖
        String infService = Context.LAYOUT_INFLATER_SERVICE;
        layoutInflater = (LayoutInflater)getContext().getSystemService(infService);  //layoutInflater=LayoutInflater.from(context);
        view = layoutInflater.inflate(R.layout.ui_linearlayout, this, true);   //獲取當前控件的引用,使用this也行
        //獲取對子控件的引用
        editText = (EditText)findViewById(R.id.ui_linearlayout_editText);
        clearButton = (Button)findViewById(R.id.ui_linearlayout_clearButton);
        //也可以使用代碼自己添加
      }

    //組合控件的自定義函數
    private void fun1(String str,Drawable Images,OnClickListener onclick){
        editText.setText(str);
        clearButton.setBackgroundDrawable(Images);
        clearButton.setOnClickListener(onclick);
    }

在activity中添加自定義控件

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.activity1_relativeLayout1);
UI_LinearLayout myview = new UI_LinearLayout(this);
relativeLayout .addView(myview);
//myview.fun1(str, Images, onclick);   //調用內部函數

在窗口ui佈局的xml中添加自定義控件

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *