1. 程式人生 > >自定義View之繼承LinearLayout

自定義View之繼承LinearLayout

自定義View有三種方式:

1:完全自定義View,也就是繼承View,或者ViewGroup還有就是SurfaceView

2:半自定義View,所謂半自定View就是繼承SDK中已經寫好的一些View,比如LinearLayout、RelativeLayout、FragmentLayout、Dialog等等

3:混合自定義View,混合自定義就是在XML檔案中引入已經寫好的自定義View,例如:<com.xxx.view.MyView ><com.xxx.view.MyView/>

今天要給大家講的是,如何半自定義View


在繼承LinearLayout的時候,必須實現以下4種構造器中的一種,也可以是多種

每個構造器的用途都不同,不瞭解的可以看一下 

今天先教大家使用第一種,LinearLayout(Context context)

public class MyView extends LinearLayout {

    private Button button;
    public MyView(final Context context) {
        super(context);
button = new Button(context);
/**
         * 方式1:
         */
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300,100);
// button.setLayoutParams(layoutParams); /** * 方式2: */ addView(button); LinearLayout.LayoutParams layoutParams = (LayoutParams) button.getLayoutParams(); layoutParams.weight = 300; layoutParams.height = 100; button.setLayoutParams(layoutParams); button.setText("我是一個按鈕"); button.setOnClickListener(new
OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context,"點選了",Toast.LENGTH_SHORT).show(); } }); } }
public class MainActivity extends AppCompatActivity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}

}


LinearLayout.LayoutParams
這句的作用是為 button 設定它的 width 和 height
addView(button);
因為是繼承自LinearLayout,所以addView的作用就是將一個view物件,新增入LinearLayout的“肚子裡”,其方式與以下完全相同
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
    <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是一個按鈕"/>
</LinearLayout>

由於是繼承自LinearLayout,所以習慣寫XML佈局的同學注意了,java方式實現的方法與XML中的完全相同