2024年4月1日发(作者:)

由麦可网整理,转载请注明出处

 Android ViewManager实例

LinearLayout实现了ViewManager接口。

当LinearLayout调用addView (View view, Params params)方法后,

LinearLayout中会增加一个子视图,并重新绘制自己。子视图的布局参数是在addView()

方法中指定的params。

LinearLayout调用removeView (View view)方法后,LinearLayout会移除view所引用

的实例,并重新绘制自己。view必须是LinearLayout中某个子视图对象实例的引用。

LinearLayout调用UpdateViewLayout (View view, Params params),

会使得view所引用的实例使用params重

如下:

Java代码 ;









































List;

ty;

t;

;

y;

;

oup;

Params;

;

Layout;

ew;

publicclassViewManagerDemoextendsActivity{

/**Calledwhentheactivityisfirstcreated.*/

ButtonaddViewButton;

ButtonremoveViewButton;

LinearLayoutmyLayout;

privateLinkedListtextViews;

booleanisEdited=false;

Contextcontext;

@Override

publicvoidonCreate(BundlesavedInstanceState){

te(savedInstanceState);

由麦可网整理,转载请注明出处

 setContentView();



 textViews=newLinkedList();

 findViews();

 setListeners();

 context=this;

 }



 privatevoidfindViews(){

 addViewButton=(Button)ewById(w);

 removeViewButton=(Button)ewById(View);

 myLayout=(LinearLayout)ewById(ut);



 st((TextView)ewById(ew_1));

 st((TextView)ewById(ew_2));

 st((TextView)ewById(ew_3));

 }



 privatevoidsetListeners(){

 if(addViewButton!=null){

 lickListener(kListener(){



 publicvoidonClick(Viewv){

 TextViewmyTextView=newTextView(context);

 t("IamnewTextView.");

 vity();



 st(myTextView);



 w(myTextView,

 Params(_PARENT,_CO

NTENT));

 //调用addView

 if(!isEdited){

 isEdited=true;

 ViewLayout(t(),

 Params(_PARENT,_

CONTENT));













}

}

});

}

if(removeViewButton!=null){

由麦可网整理,转载请注明出处











lickListener(kListener(){

publicvoidonClick(Viewv){

TextViewtView=();

View(tView);//移除View

 if(isEdited){

 isEdited=false;

 ViewLayout(t(),

 Params(_CONTENT,

P_CONTENT));











}

}

});

}

}

 }

如下:

Java代码



















































android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">