在Activity中建立一個LinearLayout,建立一個scrollHorizon對象(scrollHorizon繼承自ViewGroup),在scrollHorizon中調用createLayout函數來載入myView(繼承自View)對象,然後調用deleteAllView函數來刪除所有的視圖。
scrollHorizon代碼:
public class scrollHorizon extends ViewGroup {private Context context;public scrollHorizon(Context context) {super(context);this.context = context;createLayout();deleteAllView();}@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {int childCount = this.getChildCount();int childLeft = 0;int childTop = 0;for(int i = 0; i < childCount; i++){View child = getChildAt(i);child.setVisibility(View.VISIBLE);child.measure(r - l, b - t);child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(),childTop + child.getMeasuredHeight());if(childLeft <= 320){childLeft = childLeft + child.getMeasuredWidth();}else{childLeft = 0;childTop = childTop + child.getMeasuredHeight();}}}public void createLayout(){Resources resource = this.getResources();PackageManager pmanager = context.getPackageManager();final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> list = pmanager.queryIntentActivities(mainIntent, 0); for( int i = 0; i < list.size(); i++){ int icon = R.drawable.contacts_button_normal; LinearLayout linear = new LinearLayout(context); linear.setLayoutParams(new LayoutParams(45, 45)); linear.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon)); ImageView image2 = new ImageView(context); image2.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon)); Drawable drawable = resource.getDrawable(icon); ImageView image = new ImageView(context); image.setBackgroundDrawable(drawable); linear.addView(image2); linear.addView(image); this.addView(linear); }}public void deleteAllView(){int size = this.getChildCount();for( int i = 0; i < size; i++){this.removeViewAt(i);}}}
myView代碼:
public class myView extends View {public myView(Context context) {super(context);setLayoutParams(new LayoutParams(40,40));}}
主Activity代碼:
public class scrollHorizonTest extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linear = new LinearLayout(this); scrollHorizon horizon = new scrollHorizon(this); linear.addView(horizon); this.setContentView(linear); }}
顯示結果:
如果不調用deleteAllView函數,那程式沒有問題,可以正常的進行顯示,但調用deleteAllView函數存在null 指標異常。
原因為:當你刪除掉第一個View後(假設總共有兩個View),當前ViewGroup的子視圖只有一個,而這個子視圖的位置變為0,所以當你調用removeViewAt(1)時會出現null 指標異常,正確的刪除方法應該是將deleteAllView函數中的removeViewAt(i)修改為removeViewAt(0);