ViewManager的Demo

LinearLayout实现了ViewManager接口。

 

当LinearLayout调用addView (View view, ViewGroup.LayoutParams params)方法后,LinearLayout中会增加一个子视图,并重新绘制自己。子视图的布局参数是在addView()方法中指定的params。

 

LinearLayout调用removeView (View view)方法后,LinearLayout会移除view所引用的实例,并重新绘制自己。view必须是LinearLayout中某个子视图对象实例的引用。


LinearLayout调用UpdateViewLayout (View view, ViewGroup.LayoutParams params),会使得view所引用的实例使用params重新绘制自己。iew必须是LinearLayout中某个子视图对象实例的引用。

 

ViewManagerDemo.java如下:

package com.cnAndroid.api; import java.util.LinkedList; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class ViewManagerDemo extends Activity { /** Called when the activity is first created. */ Button addViewButton; Button removeViewButton; LinearLayout myLayout; private LinkedList textViews; boolean isEdited = false; Context context ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textViews = new LinkedList(); findViews(); setListeners(); context = this; } private void findViews(){ addViewButton = (Button)this.findViewById(R.id.addView); removeViewButton = (Button)this.findViewById(R.id.removeView); myLayout = (LinearLayout)this.findViewById(R.id.liLayout); textViews.addFirst((TextView)this.findViewById(R.id.textView_1)); textViews.addFirst((TextView)this.findViewById(R.id.textView_2)); textViews.addFirst((TextView)this.findViewById(R.id.textView_3)); } private void setListeners(){ if(addViewButton != null){ this.addViewButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView myTextView = new TextView(context); myTextView.setText("I am new TextView."); myTextView.setGravity(Gravity.CENTER); textViews.addFirst(myTextView); myLayout.addView(myTextView, new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); //调用addView if(!isEdited){ isEdited = true; myLayout.updateViewLayout(textViews.getLast(), new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } } }); } if(removeViewButton != null){ this.removeViewButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView tView = textViews.remove(); myLayout.removeView(tView); //移除View if(isEdited){ isEdited = false; myLayout.updateViewLayout(textViews.getLast(), new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } } }); } } } 

 

main.xml如下:

你可能感兴趣的:(Android)