Android ViewGroup删除子视图时应该注意的一个问题
Android ViewGroup删除子视图时应该注意的一个问题
在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();
- }
- @Override
- protected 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函数存在空指针异常。
原因为:当你删除掉第一个View后(假设总共有两个View),当前ViewGroup的子视图只有一个,而这个子视图的位置变为0,所以当你调用removeViewAt(1)时会出现空指针异常,正确的删除方法应该是将deleteAllView函数中的removeViewAt(i)修改为removeViewAt(0);
评论暂时关闭