[英]How to call an array filled with elements from another class?
How do I get elements of a rectangle array r[] which I fill in DrawView class, from another class named MainView? 如何从另一个名为MainView的类中获取DrawView类中填充的矩形数组r []的元素?
I have tried out several solutions but either I only get an array filled with the last element of the DrawView class array or nullpointer exception. 我已经尝试了几种解决方案,但是要么我只得到了一个用DrawView类数组的最后一个元素填充的数组,要么是nullpointer异常。
Eg the code below, when I try to export the array into MainView (inside the cycle, r[i]=drawView.r[i]) from DrawView, it gives an array wholly filled with the last element of DrawView rectangle array. 例如下面的代码,当我尝试从DrawView将数组导出到MainView中(在循环内,r [i] = drawView.r [i]),它给出了一个数组,该数组完全填充了DrawView矩形数组的最后一个元素。 But I would like to export to MainView exactly the same array which I filled in the DrawView.
但我想将与DrawView中填充的数组完全相同的数组导出到MainView。
Any ideas what should I change? 有什么想法我应该改变什么?
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 class: 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;
}
});
}
}
There is one thing you should understand very well: objects are referenced in java. 您应该非常了解一件事: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. r[0]
和r[1]
引用相同的对象。 Therefore, if you do 因此,如果您这样做
System.out.println(r[0].right);
you will see that prints 2
, instead of 1
. 您会看到打印
2
,而不是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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.