我创建了一个 For 循环,可以创建一些动态的相关布局。我有一个包含一些元素的arrayList,称为“photosPathList”。此 arrayList 的大小用于定义最大循环数。我正在编写的这段代码位于 Android 活动的 onResume() 方法中。有一件事我不明白。如果我在循环内记录 i 索引,它会正确增加,并且在每个循环中它取 +1 值。但是,如果我单击相对布局侦听器,则 i 索引始终具有最后一个循环位置。因此,如果我创建 4 个相对布局并单击第一个,则相对布局内的日志向我显示数字 3。这是不正确的,因为它应该显示数字 0。你同意吗?那么我做错了什么?
for (i=0; i<= photosPathList.size()-1; i++) {
//RELATIVE LAYOUT
RelativeLayout relativeLayout = new RelativeLayout(this); //create a new relative layout
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, //set main params about the width and height
RelativeLayout.LayoutParams.FILL_PARENT));
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor)); //set background color
LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
relativeParams.setMargins(20, 20, 20, 0);
relativeLayout.setLayoutParams(relativeParams); //set declared params about layout to the relativeLayout
relativeLayout.requestLayout();
Log.i("index",""+i);
Log.i("current path",""+photosPathList.get(i).toString());
relativeLayout.setOnClickListener(new View.OnClickListener(){ //create a listener about the layout. When a user press a point inside the relative layout a new activity should be created
@Override
public void onClick(View v){
Intent photoDetailsActivity = new Intent(
getApplicationContext(),
PhotoDetails.class //assign the class for create a new intent
);
Log.i("index2",""+i);
photoDetailsActivity.putExtra("photoDetailsImagePath", photosPathList.get(i).toString());
photoDetailsActivity.putStringArrayListExtra("photosPathList" , photosPathList);
photoDetailsActivity.putStringArrayListExtra("formatPhotoList", formatPhotoList);
photoDetailsActivity.putStringArrayListExtra("numberCopiesPhotoList", numberCopiesPhotoList);
photoDetailsActivity.putStringArrayListExtra("pricePhotoList", pricePhotoList);
startActivity(photoDetailsActivity); //let's start the new activity
}
});
}
谢谢