我开发了一个代码,它将动态创建ImageView并将其放在屏幕上。但是当我在模拟器上测试它时会创建许多imageview,但是在手机上测试时只会创建一个imageView,第二次应用程序崩溃。这是代码。当我创建一个ImageView时在我的单元格上进行usb调试,之后将其他图像添加到图像视图单击按钮库打开以选择其他图像,但是当选择其他图像时,最后一个图像视图将被删除。我认为当画廊开放时,活动再次开始。有人可以告诉我哪里出错了。
package info.androidhive.slidingmenu;
public class DragActivity extends Activity {
RelativeLayout relativeLayout;
ImageView imgView;
private int nfontSize;
Bitmap originalBitmap, image;
int height1, width1;
final int SELECT_IMAGE = 1;
Uri selectedImage;
Bitmap yourSelectedImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag);
Intent intent = getIntent();
int nImageId = intent.getIntExtra("drawableId", 0);
imgView = (ImageView) findViewById(R.id.imageViewEdit);
imgView.setBackgroundResource(nImageId);
relativeLayout = (RelativeLayout) findViewById(R.id.drag_activity_layout);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// Dimension x,y of device to create a scaled bitmap having similar
// dimnstinos to screen size
height1 = displayMetrics.heightPixels;
width1 = displayMetrics.widthPixels;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_IMAGE:
if (resultCode == RESULT_OK) {
selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filepath = cursor.getString(columnIndex);
cursor.close();
yourSelectedImage = BitmapFactory.decodeFile(filepath);
if (yourSelectedImage != null) {
final DragImageView dynamicImgView = new DragImageView(
getApplicationContext(), yourSelectedImage);
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
dynamicImgView.setLayoutParams(params);
relativeLayout.addView(dynamicImgView);
}
}
break;
default:
break;
}
}
void saveImage(Bitmap bmpImg) {
String RootDir = Environment.getExternalStorageDirectory() + File.separator + AppConstant.SavedFolderName;
File myDir = new File(RootDir);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Invite-"+ n + ".jpg";
File file = new File(myDir,fname);
if(file.exists())file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
Toast.makeText(DragActivity.this,
"Image saved to folder", Toast.LENGTH_LONG)
.show();
bmpImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_addText:
final Dialog alertDialog = new Dialog(this);
alertDialog.setContentView(R.layout.custom_alert_dialog);
alertDialog.setTitle("Add Text");
String[] colors = { "RED", "GREEN", "BLUE", "BLACK", "WHITE",
"YELLOW", "CYAN" };
String[] fonts = { "Wedding", "Birthday", "Events", "Business" };
// set custom dialog components
final EditText etUserTxt = (EditText) alertDialog
.findViewById(R.id.editText_userTxt);
final TextView tvFontSize = (TextView) alertDialog
.findViewById(R.id.textView_fontsize);
final TextView tvErrorMsg = (TextView) alertDialog
.findViewById(R.id.textView_errorTxt);
Button btnOk = (Button) alertDialog.findViewById(R.id.button_ok);
Button btnCancel = (Button) alertDialog
.findViewById(R.id.button_cancel);
final Spinner colorSpinner = (Spinner) alertDialog
.findViewById(R.id.spinnerColor);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, colors);
colorSpinner.setAdapter(adapter);
final Spinner fontFaceSpinner = (Spinner) alertDialog
.findViewById(R.id.spinnerFontFace);
ArrayAdapter<String> adapterFont = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, fonts);
fontFaceSpinner.setAdapter(adapterFont);
SeekBar seekBar_fontSize = (SeekBar) alertDialog
.findViewById(R.id.seekBar1);
nfontSize = 20;
fontFaceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Typeface tf;
switch (position) {
case 0:
tf = Typeface.createFromAsset(getAssets(), "fonts/AnkeCalligraph.TTF");
tvFontSize.setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
tvFontSize.setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(getAssets(), "fonts/Subway.ttf");
tvFontSize.setTypeface(tf);
break;
case 3:
tf = Typeface.createFromAsset(getAssets(), "fonts/timesbi.ttf");
tvFontSize.setTypeface(tf);
break;
default:
tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
tvFontSize.setTypeface(tf);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
seekBar_fontSize
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
// TODO Auto-generated method stub
tvFontSize.setTextSize(progress);
nfontSize = progress;
}
});
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
}
});
btnOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String userTxt = etUserTxt.getText().toString();
int colorId = colorSpinner.getSelectedItemPosition();
int fontId = fontFaceSpinner.getSelectedItemPosition();
final DragView textView = new DragView(
getApplicationContext());
textView.setText(userTxt);
textView.setTextSize(nfontSize);
switch (colorId) {
case 0:
textView.setTextColor(Color.RED);
break;
case 1:
textView.setTextColor(Color.GREEN);
break;
case 2:
textView.setTextColor(Color.BLUE);
break;
case 3:
textView.setTextColor(Color.BLACK);
break;
case 4:
textView.setTextColor(Color.WHITE);
break;
case 5:
textView.setTextColor(Color.YELLOW);
break;
case 6:
textView.setTextColor(Color.CYAN);
break;
default:
break;
}
Typeface tf;
switch (fontId) {
case 0:
tf = Typeface.createFromAsset(getAssets(), "fonts/AnkeCalligraph.TTF");
textView.setTypeface(tf);
break;
case 1:
tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
textView.setTypeface(tf);
break;
case 2:
tf = Typeface.createFromAsset(getAssets(), "fonts/Subway.ttf");
textView.setTypeface(tf);
break;
case 3:
tf = Typeface.createFromAsset(getAssets(), "fonts/timesbi.ttf");
textView.setTypeface(tf);
break;
default:
tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
textView.setTypeface(tf);
break;
}
final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(params);
relativeLayout.addView(textView, params);
if (userTxt.isEmpty()) {
tvErrorMsg.setText("Please enter the text");
tvErrorMsg.setTextColor(Color.RED);
tvErrorMsg.setTextSize(20);
} else {
alertDialog.dismiss();
}
}
});
alertDialog.show();
return true;
case R.id.action_savePicture:
View v = findViewById(R.id.drag_activity_layout);
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
saveImage(b);
return true;
case R.id.action_addImage:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_IMAGE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static int getFilesCount(File file) {
int count = 0;
if(file != null){
Log.d("File Check","File is not empty");
File[] files = file.listFiles();
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
}
else{
Log.d("File Check","File is not empty");
return 0;}
return count;
}
}
答案 0 :(得分:0)
我认为这一行会产生错误:
final DragImageView dynamicImgView = new DragImageView(
getApplicationContext(), yourSelectedImage);
我的第一个建议是,当你运行代码一段时间时,你试图将变量(dynamicImgView)声明为一段时间。变量已经存在,因为它引用了它添加到的相对布局:
relativeLayout.addView(dynamicImgView);
我的第二个分析是变量无法在第二个时间内更改,因为它是用&#34; final&#34;关键字。
来源:http://en.wikipedia.org/wiki/Final_(Java)
我知道变量离开函数后不应该存在(因为那时你已经超出了这个变量的有效范围),但由于对RelativeLayout的引用,我认为它仍然存在于系统中。
这可以帮助你=)。
最好的问候 添