2016-10-20 156 views
-8

我是java noob(但學習速度很快),我一直試圖在我的MainActivity中引入代碼片段到android項目中。在Android項目中複製onCreate(Bundle)

我的問題是,我有兩個衝突的onCreate(捆綁)行,其他答案說只是刪除一個!當我註釋掉最頂層的代碼時,大部分代碼會引發錯誤,當我註釋掉第二個代碼時,它會在我正在使用的代碼段中導致出現錯誤,即,它會停止setOnClickListener,我認爲這是我將用於選擇的按鈕上的一個偵聽器一個圖像。

錯誤:

Error:(273, 24) error: method onCreate(Bundle) is already defined in class 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); 
       } 
      } 
     } 


} 
+2

你怎麼樣移動'btnSelectPhoto'按鈕初始化和'setOnClickListener'方法在setContentView之後的第一個onCreate方法中,然後移除第二個onCreate? –

+1

你有多個'super.onCreate(savedInstanceState);' –

+0

請看看[問]和[mcve]。我確定那些導入不是用來理解你的代碼的。你的問題不應該再長一些。 – xenteros

回答

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 studio會感到困惑。你的android studio無法檢測到編譯的方法。

+0

感謝,通過合併你所說的話和@ρяσѕρєяK的評論它完美的工作,也許你可以考慮通過正確格式化來編輯你的答案anmd聲明它應該被剪切,然後直接在第一個'onCreate'方法後粘貼,謝謝。 (我會建議一個編輯,但它說有人正在做這個,所以我希望他們建議一樣),我會標記這個正確的答案一旦格式化和解釋完全/更好) – Jackherer

相關問題