我是一个java noob(但学习速度很快),我一直在尝试在Android项目中将代码片段引入我的MainActivity。
我的问题是我有两条相互冲突的onCreate(捆绑)行,其他答案只是删除一行!当我注释掉顶部的大部分代码抛出错误时,当我注释掉第二个时,它会导致我正在使用的片段出现错误,即它会停止setOnClickListener,我认为它是一个监听器,我会用来选择一个图像。
错误:
错误:(273,24)错误:方法onCreate(Bundle)已在类MainActivity中定义
这是我的MainActivity.java:
public class MainActivity extends AppCompatActivity {
private EditText inputStrain, inputNumOfZs, EditText, inputShortDesc;
private TextInputLayout inputLayoutStrain, inputLayoutNumOfZs, inputLayoutPricePerOz, inputLayoutShortDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Please enter all the details requested.", Toast.LENGTH_SHORT).show();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputLayoutStrain = (TextInputLayout) findViewById(R.id.input_layout_strain);
inputLayoutNumOfZs = (TextInputLayout) findViewById(R.id.input_layout_num_of_zs);
inputLayoutShortDesc = (TextInputLayout) findViewById(R.id.input_layout_short_desc);
inputLayoutPricePerOz = (TextInputLayout) findViewById(R.id.input_layout_price_per_oz);
inputStrain = (EditText) findViewById(R.id.input_strain);
inputNumOfZs = (EditText) findViewById(R.id.input_num_of_zs);
EditText inputPricePerOz = (EditText) findViewById(R.id.input_price_per_oz);
inputShortDesc = (EditText) findViewById(R.id.input_short_desc);
Button btnAdd = (Button) findViewById(R.id.btn_add);
inputStrain.addTextChangedListener(new MyTextWatcher(inputStrain));
inputNumOfZs.addTextChangedListener(new MyTextWatcher(inputNumOfZs));
inputShortDesc.addTextChangedListener(new MyTextWatcher(inputShortDesc));
inputPricePerOz.addTextChangedListener(new NumberTextWatcher(inputPricePerOz, "#,###"));
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitForm();
}
});
}
/**
* Validating form
*/
private void submitForm() {
if (!validateStrain()) {
return;
}
if (!validateNumOfZs()) {
return;
}
if (!validateShortDesc()) {
return;
}
Toast.makeText(getApplicationContext(), "@string/add_new_oz_toast", Toast.LENGTH_SHORT).show();
}
// validate proper correctness of user input
// could make this to toast? if user doesnt enter correct/required field
private boolean validateStrain() {
if (inputStrain.getText().toString().trim().isEmpty()) {
inputLayoutStrain.setError(getString(R.string.err_msg_strain));
requestFocus(inputStrain);
return false;
} else {
inputLayoutStrain.setErrorEnabled(false);
}
return true;
}
private boolean validateNumOfZs() {
if (inputNumOfZs.getText().toString().trim().isEmpty()) {
inputLayoutNumOfZs.setError(getString(R.string.err_msg_num_of_zs));
requestFocus(inputNumOfZs);
return false;
} else {
inputLayoutNumOfZs.setErrorEnabled(false);
}
return true;
}
private boolean validatePricePerOz() {
if (EditText.getText().toString().trim().isEmpty()) {
inputLayoutPricePerOz.setError(getString(R.string.err_msg_price_per_oz));
requestFocus(EditText);
return false;
} else {
inputLayoutNumOfZs.setErrorEnabled(false);
}
return true;
}
private boolean validateShortDesc() {
if (inputShortDesc.getText().toString().trim().isEmpty()) {
inputLayoutShortDesc.setError(getString(R.string.err_msg_short_desc));
requestFocus(inputShortDesc);
return false;
} else {
inputLayoutShortDesc.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
// a text watcher to ensure the text is input as it should be
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_strain:
validateStrain();
break;
case R.id.input_num_of_zs:
validateNumOfZs();
break;
case R.id.input_price_per_oz:
validatePricePerOz();
break;
case R.id.input_short_desc:
validateShortDesc();
break;
}
}
}
//my number text watcher for making price of oz a currency
public class NumberTextWatcher implements TextWatcher {
private final DecimalFormat df;
private final DecimalFormat dfnd;
private final EditText et;
private boolean hasFractionalPart;
private int trailingZeroCount;
NumberTextWatcher(EditText inputPricePerOz, String pattern) {
df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.00");
this.et = inputPricePerOz;
hasFractionalPart = false;
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
if (s != null && !s.toString().isEmpty()) {
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
StringBuilder trailingZeros = new StringBuilder();
while (trailingZeroCount-- > 0)
trailingZeros.append('0');
et.setText(df.format(n) + trailingZeros.toString());
} else {
et.setText(dfnd.format(n));
}
et.setText("@string/currency_symbol".concat(et.getText().toString()));
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel < et.getText().length()) {
et.setSelection(sel);
} else if (trailingZeroCount > -1) {
et.setSelection(et.getText().length() - 3);
} else {
et.setSelection(et.getText().length());
}
} catch (NumberFormatException | ParseException e) {
e.printStackTrace();
}
}
et.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int index = s.toString().indexOf(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
trailingZeroCount = 0;
if (index > -1) {
for (index++; index < s.length(); index++) {
if (s.charAt(index) == '0')
trailingZeroCount++;
else {
trailingZeroCount = 0;
}
}
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
ImageView viewImage;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.btnSelectPhoto);
//viewImage = (ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
答案 0 :(得分:0)
如果您从第二个onCreate:
中删除此代码b = (Button)findViewById(R.id.btnSelectPhoto);
//viewImage = (ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});
并在第一个onCreate之后直接粘贴在setContentView方法之后。我认为这会起作用。
P.S
如果你有2 onCreate
,你的android工作室将会感到困惑。你的android工作室无法检测将编译哪种方法。