0

MainView という名前の別のクラスから、DrawView クラスに入力する四角形配列 r[] の要素を取得するにはどうすればよいですか?

私はいくつかの解決策を試しましたが、DrawView クラス配列の最後の要素で満たされた配列のみを取得するか、nullpointer 例外を取得します。

たとえば、以下のコードでは、DrawView から配列を MainView (サイクル内、r[i]=drawView.r[i]) にエクスポートしようとすると、DrawView 四角形配列の最後の要素で完全に満たされた配列が得られます。しかし、DrawView に入力したのとまったく同じ配列を MainView にエクスポートしたいと思います。

何を変更すればよいですか?

public class DrawView extends View {  
   public Rect [] r = new Rect[81];
   Rect r2= new Rect(left, top, right, bottom);
   int m=0;
   @Override
   public void onDraw(Canvas canvas) {
     //...........some calculations of variables leftPosFirst etc.......//
     int i=0;
     while(i<9){
         int j=0;
         while(j<9){        
             try{
                if(m<81){
                    r2.left=leftPosFirst+1;
                    r2.top=(heightRect+heightRect*j)+1;
                    r2.right=rightPosFirst-1;
                    r2.bottom=(heightRect+heightRect*(j+1))-1;
                    r[m]=r2;
                    m++;
                }
             } catch (Exception ex){}
             j++;
         }
         i++;
     }
  } 
} 

MainView.java クラス:

public class MainActivity extends Activity implements OnTouchListener{
  DrawView drawView;
  int m=0;
  Rect[] r = new Rect[81];
  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     drawView = new DrawView(this);
     setContentView(drawView);
     drawView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    int i;
                    for (i=0; i<81; i++) {
                       try{
                         r[i] = drawView.r[i];
                         System.out.println(r[i]);
                       } catch(Exception e){}
                    }
                    return true;
                }
            }
            return false;
        }
    });
  }
}
4

1 に答える 1

0

There is one thing you should understand very well: objects are referenced in java. That is, if I write the following snippet:

Rect r[] = new Rect[2];
Rect r2 = new Rect(0, 0, 1, 1);
r[0] = r2;
r2.right = 2;
r[1] = r2;

both r[0] and r[1] refer to the same object. Therefore, if you do

System.out.println(r[0].right);

you will see that prints 2, instead of 1.

What you need to do is create a new object every time, instead of modifying the same object.

Use

if(m<81){
    r2 = new Rect(leftPosFirst+1,
                  heightRect+heightRect*j)+1,
                  rightPosFirst-1,
                  heightRect+heightRect*(j+1))-1);
    r[m]=r2;
    m++;
}
于 2013-05-05T11:03:57.920 に答える