2014-03-30 117 views
1

我試圖建立自定義數字選擇器,每次點擊+或 - 按鈕時,我的應用程序崩潰。我在MainActivity.java中沒有收到任何錯誤。 有人知道可能是什麼情況? 下面是代碼:點擊一個按鈕時,應用程序崩潰

public class MainActivity extends Activity { 

    TextView tvHeight; 
    int counter = 0; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Button heightMinus = (Button) findViewById(R.id.height_min); 
     Button heightPlus = (Button) findViewById(R.id.height_plus); 
     tvHeight = (TextView) findViewById(R.id.textViewHeight); 

     heightPlus.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       counter++; 
       tvHeight.setText(counter); 

      } 
     }); 

     heightMinus.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       counter--; 
       tvHeight.setText(counter); 

      } 
     }); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
} 
+0

你看看logcat輸出了嗎? – donfuxx

+0

你爲什麼把這個標籤標記爲'numberpicker'? – Raghunandan

回答

3

更改此

tvHeight.setText(counter); 

tvHeight.setText(String.valueOf(counter)); 

看那方法

public final void setText (int resid) 

public final void setText (CharSequence text) 

使用第一種方法,Android會查找帶有已標識id的資源(如果找不到),您將獲得ResourceNotFoundException。有一個是int,它是Resource Id,另一個是CharacterSequecne

+1

'counter +「」'應該也能工作。 – donfuxx

+0

非常感謝您的明確解釋。 – Markonionini

3

你需要調用setText方法,期待CharSequence作爲參數。因此,與

tvHeight.setText(String.valueOf(counter)); 

目前你打電話setText(int resid)將試圖找到您在strings.xml文件中定義的字符串資源ID替換

tvHeight.setText(counter); 

所以我猜你的代碼會拋出一個ResourceNotFoundException

+0

非常感謝。這非常有幫助。 – Markonionini

相關問題