如何在没有类强制转换异常的情况下重构findViewById?

时间:2015-05-03 17:43:41

标签: android classcastexception findviewbyid

通常当我的Android应用程序中有很多元素时,onCreate看起来像这样:

    PointF pt1l = new PointF(canvas.getWidth()/2+40, (float)newPosY-canvas.getWidth()/40);//canvas.getWidth()/40
    PointF pt2l = new PointF(canvas.getWidth()/2+40, (float)newPosY+canvas.getWidth()/40);
    PointF midl = new PointF(canvas.getWidth()/2+30, (float)newPosY+canvas.getWidth()/40);

    PointF pt1r = new PointF(canvas.getWidth()/2-40, (float)newPosY-canvas.getWidth()/40);
    PointF pt2r = new PointF(canvas.getWidth()/2-40, (float)newPosY+canvas.getWidth()/40);
    PointF midr = new PointF(canvas.getWidth()/2-30, (float)newPosY+(canvas.getWidth()/40)/2);

    Path pathLeft = new Path();
    //pathLeft.setFillType(Path.FillType.EVEN_ODD);
    pathLeft.moveTo(pt1l.x,pt1l.y);
    pathLeft.quadTo(midl.x,midl.y,pt2l.x,pt2l.y);

    Path pathRight = new Path();
    //pathRight.setFillType(Path.FillType.EVEN_ODD);
    pathRight.moveTo(pt1r.x,pt1r.y);
    pathRight.quadTo(midr.x,midr.y,pt2r.x,pt2r.y);
    Paint curveLineR = new Paint();
    curveLineR.setColor(Color.GREEN);

    Paint curveLineL = new Paint();
    curveLineL.setColor(Color.GREEN);

    Paint circle = new Paint();
    circle.setColor(Color.GREEN);

    canvas.drawPath(pathLeft, curveLineL);
    canvas.drawPath(pathRight, curveLineR);
    //canvas.drawCircle(canvas.getWidth()/2,canvas.getHeight()/2,canvas.getWidth()/30,circle);
    canvas.drawCircle(canvas.getWidth()/2,(float)newPosY,canvas.getWidth()/40,circle);

Android需要为应用中的每个文本,图片,按钮等执行此类强制转换。但是文本,图像,按钮,切换器都是View类的子类!

我尝试将所有视图添加到一个Views数组中,并像这样循环:

  onCreate(){

   ImageButton b1 = (ImageButton)findViewById(R.id.b1) ;
   ImageButton b2 = (ImageButton)findViewById(R.id.b2) ;
   ImageVuew v3 = (ImageButton)findViewById(R.id.v3) ;
   ViewSwitcher v4 = (ViewSwitcher)findViewbyId(R.id.v4) ;
   TextView v5 = (TextView)findViewById(R.id.v5) ;

   //and so on
  }

它可能会抛出类强制转换异常

有没有办法让它以聪明的方式做到?

1 个答案:

答案 0 :(得分:1)

试试library Butterknife,我认为你正在寻找它。它将使您的代码更清洁:)

网站上的例子是:

class ExampleActivity extends Activity {
  @InjectView(R.id.title) TextView title;
  @InjectView(R.id.subtitle) TextView subtitle;
  @InjectView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.inject(this);
    // TODO Use "injected" views...
  }
}