2017-09-03 77 views
-2

所以我正在開發Android程序,顯示我的年齡給出了他們的出生年份。但我的應用程序不顯示任何答案,它只顯示0按鈕時按下。 您能否請我建議我去哪裏錯了。並告訴我如何顯示2017年之間的差異 - myAge。如何讓我的顯示在我的textView在Android?

public class MainActivity extends AppCompatActivity { 

Button press; 
EditText editText; 
TextView enterText; 
int myAge; 
int yearOfBirth; 
int year = 2017; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    editText = (EditText)findViewById(R.id.editText) ; 
    enterText = (TextView)findViewById(R.id.entertext); 
    press = (Button)findViewById(R.id.press); 

     try 
     { 
      yearOfBirth = Integer.parseInt(editText.getText().toString()); 

      }catch(NumberFormatException e) 
      { 
       e.printStackTrace(); 
      } 



      press.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        myAge = yearOfBirth; 
        enterText.setText(String.valueOf(myAge)); 
       } 
      }); 
    } 
} 

截圖:

enter image description here

+2

您應該從您的點擊偵聽器中獲取edittext的值。目前,您可以在應用程序啓動時獲取編輯文本的值(onCreate)。如果你想獲得編輯文本的值,當你按下一個按鈕,你需要在onClickListener – swerly

+0

並獲得正確的輸出從'yearOfBirth'減去'年' – Blasanka

回答

1

刪除

yearOfBirth = Integer.parseInt(editText.getText().toString()); 

try塊,並添加它的onClick塊內。和

代替

myAge = yearOfBirth; 

int currYear = Calendar.getInstance().get(Calendar.YEAR); 
myAge = currYear - yearOfBirth; 

把年= 2017年將僅在今年,這就是爲什麼我建議你使用Calendar類,讓你準確一年的工作。

+0

非常感謝你的代碼作品像魅力。我我對android很陌生,這有助於我快速學習新東西。謝謝 –

1

看來你只是缺少計算年齡的步驟。

你獲取正確的yearOfBirth,但你只是設置myAge到它,而不是做這樣的事情

myAge = year - yearOfBirth 

篩選。

press.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        myAge = year - yearOfBirth; // Here. 
        enterText.setText(String.valueOf(myAge)); 
       } 
      }); 
0

看起來像你計算年齡的邏輯是錯誤的。

myAge = year - yearOfBirth; //calculate age 

這應該有效。

相關問題