Button基本應用
button按鈕是一個App中非常重要的一環,主要大部分的功能觸發都用button作為主要觸發,現在就用一個比較常見的範例BMI計算來簡單介紹buttton的製作並簡單介紹一下android的大概架構:
首先先將layout的部分部屬完成
大致上外觀像這樣,一個EditText記錄身高另一個記錄體重搭配上一個觸發計算按鈕
如果要在EditText中顯示類浮水印的字,請點選該物件並於屬性中的hint輸出值(如下)
這裡在提醒一個好習慣,在介面上要輸出的文字要養成習慣要先在String.xml中定義好
在以連結上物件的方式完成,在往後維護上會容易許多問題也少掉不少(如下)
做好一個開始的介面以及一個顯示結果的介面
再來layout部屬完要開始寫Button的事件
之後到MAIN Oncreate中新增一個Listener顧名思義就是就要隨時監聽按鈕有沒有被點擊
這部分必須要再app create的階段就建構完成所以寫在oncreate
這部分必須要再app create的階段就建構完成所以寫在oncreate
final EditText height= (EditText)findViewById(R.id.editText);
final EditText weight= (EditText)findViewById(R.id.editText2);
Button calc = (Button) findViewById(R.id.button);
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resultIntent = new Intent(view.getContext(), Result.class);指定目標
resultIntent.putExtra("height", height.getText().toString());
resultIntent.putExtra("weight", weight.getText().toString());
startActivity(resultIntent);\\傳到目標layout
}
});
一旦觸發點擊後指定將height和weight藉由Intent包裝,這裡用bundle寫也可以只要改成下面這即可
在Result中接收
完成品
Intent = new Intent(view.getContext(), Result.class); bundle bundle =new bundle(); bundle.putExtra("height",height.getText().toString()); bundle.putExtra("weight",weight.getText().toString()); intent.putExtras(bundle); startActivity(resultIntent);接收:
Bundle bundle = this.getIntent().getExtras();
weight
= bundle.getString("weight");
height = bundle.getString("height");
在Result中接收
Intent intent=getIntent(); String height= intent.getStringExtra("height"); String weight= intent.getStringExtra("weight"); if(!(height.isEmpty()) || !(weight.isEmpty())){ Double heightn= Double.parseDouble(height); Double weightn= Double.parseDouble(weight); EditText result = (EditText)findViewById(R.id.editText3); result.setText(String.valueOf(weightn / (heightn * heightn) * 10000)); }
完成品
沒有留言:
張貼留言