2012-09-28 18 views
1

我盡我所能解決這個問題,但從來沒有成功,我也環顧網絡,但沒有找到我要找的東西。子字符串從毫秒的右邊數字

所以。我正在做一個秒錶應用程序,我希望它顯示毫秒,但我無法獲得正確的摘要顯示,因爲我只希望它顯示釐秒,我的意思是兩個數字,從00到99然後1秒已過去。

當我用下面的代碼運行應用程序時,它看起來像在模擬器中,我工作,(不能完全說明,因爲模擬器是緩慢和滯後的),但是當我運行它在我的銀河聯繫4.1 .1我接近力量。

任何幫助將非常感激

下面是毫秒字符串代碼:

milliseconds = String.valueOf((long)time); 
    if(milliseconds.length()==3){ 
     milliseconds = "0"+milliseconds; 
    } 
    if(milliseconds.length()<=1){ 
     milliseconds = "00"; 
    } 
    milliseconds = milliseconds.substring(milliseconds.length()-3, milliseconds.length()-1); 

完整的Java:

package com.tutorial.stopwatch; 

import android.os.Bundle; 
import android.os.Handler; 
import android.app.Activity; 
import android.view.Menu; 
import android.app.Activity; 
import android.content.res.Configuration; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.graphics.Typeface; 
import android.os.Bundle; 
import android.util.DisplayMetrics; 
import android.util.TypedValue; 
import android.view.View; 
import android.widget.Button; 

public class MainActivity extends Activity { 

    private TextView tempTextView; //Temporary TextView 
    private Button tempBtn; //Temporary Button 
    private Handler mHandler = new Handler(); 
    private long startTime; 
    private long elapsedTime; 
    private final int REFRESH_RATE = 100; 
    private String hours,minutes,seconds,milliseconds; 
    private long secs,mins,hrs,msecs; 
    private boolean stopped = false; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     checkScreenDensity(); 

     /*-------Setting the TextView Fonts-----------*/ 

     Typeface fonttimer = Typeface.createFromAsset(getAssets(), "roboto.ttf"); 
     tempTextView = (TextView) findViewById(R.id.timer); 
     tempTextView.setTypeface(fonttimer); 
     tempTextView = (TextView) findViewById(R.id.timerMs); 
     tempTextView.setTypeface(fonttimer); 
     tempTextView = (TextView) findViewById(R.id.timerHs); 
     tempTextView.setTypeface(fonttimer); 

     Typeface font = Typeface.createFromAsset(getAssets(), "roboto.ttf"); 
     tempTextView = (TextView) findViewById(R.id.backgroundText); 
     tempTextView.setTypeface(font); 
     Button tempBtn = (Button)findViewById(R.id.startButton); 
     tempBtn.setTypeface(font); 
     tempBtn = (Button)findViewById(R.id.resetButton); 
     tempBtn.setTypeface(font); 
     tempBtn = (Button)findViewById(R.id.stopButton); 
     tempBtn.setTypeface(font); 

    } 


    private void checkScreenDensity(){ 
     tempTextView = (TextView)findViewById(R.id.backgroundText); 
     switch (getResources().getDisplayMetrics().densityDpi) { 
     case DisplayMetrics.DENSITY_LOW: 
      tempTextView.setVisibility(View.GONE); 
      break; 
     case DisplayMetrics.DENSITY_MEDIUM: 
      tempTextView.setVisibility(View.GONE); 
      break; 
     case DisplayMetrics.DENSITY_HIGH: 
      tempTextView.setVisibility(View.VISIBLE); 
      break; 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 



    //---------- on click procedures - id from layout.xml ----------- 

    public void startClick (View view){ 
     showStopButton(); 
     if(stopped){ 
      startTime = System.currentTimeMillis() - elapsedTime; 
     } 
     else{ 
      startTime = System.currentTimeMillis(); 
     } 
     mHandler.removeCallbacks(startTimer); 
     mHandler.postDelayed(startTimer, 0); 
    } 

    public void stopClick (View view){ 
     hideStopButton(); 
     mHandler.removeCallbacks(startTimer); 
     stopped = true; 
    } 

    public void resetClick (View view){ 
     hideStopButton(); 
     mHandler.removeCallbacks(startTimer); 
     stopped = false; 
     ((TextView)findViewById(R.id.timer)).setText("00:00"); 
     ((TextView)findViewById(R.id.timerMs)).setText(":00"); 
     ((TextView)findViewById(R.id.timerHs)).setText("00:"); 
    } 

    //---------- Button change (start/reset to stop button) 
    private void showStopButton(){ 
     ((Button)findViewById(R.id.startButton)).setVisibility(View.GONE); 
     ((Button)findViewById(R.id.resetButton)).setVisibility(View.VISIBLE); 
     ((Button)findViewById(R.id.stopButton)).setVisibility(View.VISIBLE); 
    } 

    private void hideStopButton(){ 
     ((Button)findViewById(R.id.startButton)).setVisibility(View.VISIBLE); 
     ((Button)findViewById(R.id.resetButton)).setVisibility(View.VISIBLE); 
     ((Button)findViewById(R.id.stopButton)).setVisibility(View.GONE); 
    } 

    //-------- time from MiliSeconds to regular time --------------------------------- 

    private void updateTimer (float time){ 
     secs = (long)(time/1000); 
     mins = (long)((time/1000)/60); 
     hrs = (long)(((time/1000)/60)/60); 

     /* Setting the timer text to the elapsed time */ 
     ((TextView)findViewById(R.id.timerHs)).setText(hours + ":"); 
     ((TextView)findViewById(R.id.timer)).setText(minutes + ":" + seconds); 
     ((TextView)findViewById(R.id.timerMs)).setText(":" + milliseconds); 

     /* Convert the seconds to String 
     * and format to ensure it has 
     * a leading zero when required 
     */ 
     secs = secs % 60; 
     seconds=String.valueOf(secs); 
     if(secs == 0){ 
      seconds = "00"; 
     } 
     if(secs <10 && secs > 0){ 
      seconds = "0"+seconds; 
     } 

     /* Convert the minutes to String and format the String */ 

     mins = mins % 60; 
     minutes=String.valueOf(mins); 
     if(mins == 0){ 
      minutes = "00"; 
     } 
     if(mins <10 && mins > 0){ 
      minutes = "0"+minutes; 
     } 

     /* Convert the hours to String and format the String */ 

     hours=String.valueOf(hrs); 
     if(hrs == 0){ 
      hours = "00"; 
     } 
     if(hrs <10 && hrs > 0){ 
      hours = "0"+hours; 
     } 

     /* milliseconds */ 

     milliseconds = String.valueOf((long)time); 
     if(milliseconds.length()==3){ 
      milliseconds = "0"+milliseconds; 
     } 
     if(milliseconds.length()<=1){ 
      milliseconds = "00"; 
     } 
     milliseconds = milliseconds.substring(milliseconds.length()-3, milliseconds.length()-1); 




    } 

    //------------- Timer Runnnable ----------------------------------------------------------- 

    private Runnable startTimer = new Runnable() { 
      public void run() { 
       elapsedTime = System.currentTimeMillis() - startTime; 
       updateTimer(elapsedTime); 
       mHandler.postDelayed(this,REFRESH_RATE); 
      } 
     }; 

    //------------------ screen orientation fix ----------------------------------------------------------- 

     @Override 
     public void onConfigurationChanged(Configuration newConfig) { 
      super.onConfigurationChanged(newConfig); 
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
       TextView timer = (TextView) findViewById(R.id.timer); 
       timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 90); 
       TextView timerMs = (TextView) findViewById(R.id.timerMs); 
       timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40); 

      } 
      else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { 
       TextView timer = (TextView) findViewById(R.id.timer); 
       timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 70); 
       TextView timerMs = (TextView) findViewById(R.id.timerMs); 
       timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30); 

      } 
     } 



} 

UPDATE:

我編輯的代碼適合我的佈局,但我崩潰:

private void updateTimer (long time) { 
    Calendar c = Calendar.getInstance(); 
    c.setTimeInMillis(time); 

    // This will output one string in Hour:Minute:Seconds: with zeroes added 
    String h = String.format("%1$tH", c); 
    String ms = String.format("%1$tM:%1$tS", c); 
    // Unfortunately, theres no format specifier for centiseconds, so we'll have 
    // to make do with the substring of ms 
    String cs = String.format("%1$L").substring(0,2); 

    String printMe = h + ms + cs; 

    /* Setting the timer text to the elapsed time */ 
     ((TextView)findViewById(R.id.timerHs)).setText(h); 
     ((TextView)findViewById(R.id.timer)).setText(ms); 
     ((TextView)findViewById(R.id.timerMs)).setText(cs); 


} 

登錄:

09-28 19:32:29.986: D/dalvikvm(1832): GC_FOR_ALLOC freed 42K, 4% free 8005K/8259K, paused 112ms, total 118ms 
09-28 19:32:30.008: I/dalvikvm-heap(1832): Grow heap (frag case) to 9.331MB for 1536016-byte allocation 
09-28 19:32:30.116: D/dalvikvm(1832): GC_CONCURRENT freed <1K, 4% free 9504K/9799K, paused 33ms+17ms, total 109ms 
09-28 19:32:30.426: D/dalvikvm(1832): GC_FOR_ALLOC freed 3K, 2% free 9864K/10055K, paused 40ms, total 41ms 
09-28 19:32:30.756: D/gralloc_goldfish(1832): Emulator without GPU emulation detected. 
09-28 19:32:41.536: D/AndroidRuntime(1832): Shutting down VM 
09-28 19:32:41.588: W/dalvikvm(1832): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 
09-28 19:32:41.646: E/AndroidRuntime(1832): FATAL EXCEPTION: main 
09-28 19:32:41.646: E/AndroidRuntime(1832): java.util.MissingFormatArgumentException: Format specifier: 1$L 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.util.Formatter.getArgument(Formatter.java:1109) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.util.Formatter.doFormat(Formatter.java:1074) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.util.Formatter.format(Formatter.java:1040) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.util.Formatter.format(Formatter.java:1009) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.lang.String.format(String.java:1998) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.lang.String.format(String.java:1972) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at com.tutorial.stopwatch.MainActivity.updateTimer(MainActivity.java:138) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at com.tutorial.stopwatch.MainActivity.access$3(MainActivity.java:129) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at com.tutorial.stopwatch.MainActivity$1.run(MainActivity.java:155) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at android.os.Handler.handleCallback(Handler.java:615) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at android.os.Handler.dispatchMessage(Handler.java:92) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at android.os.Looper.loop(Looper.java:137) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at android.app.ActivityThread.main(ActivityThread.java:4745) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at java.lang.reflect.Method.invoke(Method.java:511) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
09-28 19:32:41.646: E/AndroidRuntime(1832):  at dalvik.system.NativeStart.main(Native Method) 

謝謝!

+0

你能後墜毀的logcat的日誌? – Eric

+0

對不起 - 錯字 - 它應該是「%1 $ tL」毫秒,而不是「%1 $ L」。這意味着:第一個參數,格式化爲時間,特別是時間的毫秒部分。我更新了我的答案,以及 – JRaymond

回答

0

你爲什麼要在字符串中處理你的時間?這隻會導致你痛苦:)的Java格式有一個更好的方式來處理時間:

// Note the long type here - that's what you're passing in anyway, best make it 
// official 
private void updateTimer (long time) { 
    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); 
    c.setTimeMillis(time); 

    // This will output one string in Hour:Minute:Seconds: with zeroes added 
    String hms = String.format("%1$tH:%1$tM:%1$tS:", c); 
    // Unfortunately, theres no format specifier for centiseconds, so we'll have 
    // to make do with the substring of ms 
    String cs = String.format("%1$tL", c).substring(0,2); 

    String printMe = hms + cs 
} 

formatter更多

+0

我剛接觸android開發,所以剛剛做了教程中的人告訴我。所以!我用你的updateTimer替換了我的updateTimer,然後進行了編輯,但是我崩潰了:private void updateTimer(long time){Calendar} c = Calendar.getInstance(); c.setTimeInMillis(time); String h = String.format(「%1 $ tH」,c); 字符串ms =字符串。格式(「%1 $ tM:%1 $ tS」,c); String cs = String.format(「%1 $ L」)。substring(0,2); String printMe = h + ms + cs; ((TextView)findViewById(R.id.timerHs)).setText(h); ((TextView)findViewById(R.id.timer))。setText(ms); ((TextView)findViewById(R.id.timerMs)).setText(cs); } – Jakob

+0

woops,我無法在回覆中添加代碼嗎? – Jakob

+0

@Harteg - 不是真的,更好地發佈作爲更新您的問題 - 同樣,發佈崩潰日誌,如果可以 – JRaymond

0

來自:http://www.java2s.com/Code/Java/Language-Basics/JavaformattedIOtheprecisionmodifier.htm

進口的java.util.Formatter;公共類MainClass { public static void main(String args []){ Formatter fmt = new Formatter();

// Format 4 decimal places. 
fmt.format("%.4f", 123.1234567); 
System.out.println(fmt); 

// Format to 2 decimal places in a 16 character field. 
fmt = new Formatter(); 
fmt.format("%16.2e", 123.1234567); 
System.out.println(fmt); 

// Display at most 15 characters in a string. 
fmt = new Formatter(); 
fmt.format("%.15s", "Formatting with Java is now easy."); 
System.out.println(fmt); 

}}

基本上你想要的東西,像fmt.format( 「%2D」,decimalNumberValue);

當然,您可以使用數字操作來構建自己的自己,但是這是內置於庫中的。

相關問題