EditText可以設置一個hint屬性,顯示的是一個不可更改的文字,可以作爲輸入框的提示用,有數據輸入時自動隱藏,比較好用
<EditText
android:id="@+id/et_num"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="請輸入數字"
android:textColorHint="#238745"/>
<Button
android:id="@+id/bt_num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加"/>
<Button
android:id="@+id/bt_num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="減"/>
<Button
android:id="@+id/bt_num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="撥號"/>
當有多個button在一個activity裏時,用activity去實現onclicklisten,再去set各自的listener時,傳一個this就好,這樣無需多次implements
那麼在需要用到不同的button時
通過獲取各自的ID值去判斷就好
對editText數據的獲取,裏面的是string,要變成int型
首選獲取 getText().toString()
然後改變類型valueOf()
再設置內容setText()
public class MainActivity extends Activity implements OnClickListener{
EditText et_num;
Button bt1;
Button bt2;
Button bt3;
int num;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_num = (EditText) findViewById(R.id.et_num);
//必須給一個初始值,否則在點擊button時會空指針異常
et_num.setText("1");
num = Integer.valueOf(et_num.getText().toString());
bt1 = (Button) findViewById(R.id.bt_num1);
bt2 = (Button) findViewById(R.id.bt_num2);
bt3 = (Button) findViewById(R.id.bt_num3);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int button = v.getId();
if (button == R.id.bt_num1) {
System.out.println("bt1 called");
num++;
settext();
}else if(button == R.id.bt_num2){
System.out.println("bt2 called");
num--;
settext();
}else if (button == R.id.bt_num3) {
System.out.println("bt3 called");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
}
//給一個點擊的範圍
private void settext() {
// TODO Auto-generated method stub
if (num <= 0 || num >= 10) {
Toast.makeText(getApplication(), "超出範圍嘍", 0).show();
/*
* 到了上下限時,比如,顯示的是1
* 仍然多次點擊,這樣顯示的數值不變,但是實際上的num值已變
* 反向點擊button時,需要點擊相應的次數才能再次從上下限開始變動
* 這些點擊就好像是無用功,用戶體驗不好,所以需要獲取到當前顯示的上下限重新賦值
*/
num = Integer.valueOf(et_num.getText().toString());
} else {
et_num.setText(Integer.toString(num));
}
}
}
關於撥號,需要一個權限
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
順便提一下,關於int和integer
integer是一個包裝類,int是基本數據類型
這個包裝類就是爲了方便我們做一些數據類型的轉變
如上面獲取號碼,從string轉到int,通過這個integer過渡了下
另外在泛型中,比如要給list填一個int類型數據,尖括號類必須是 類 ,所以也需要integer
List<Integer> nums;
Integer a = new Integer (128);
Integer b = new Integer (128);
a==b?
a.equals(b)?
Integer c = 10;
Integer d = 10;
c==d?
c.equals(d)?
false true true true
==判斷的是引用,地址,new出不同對象就不等,所以第一個是false;但是在自動裝箱中,如果裝的是字節,很小,值相等時沒有開闢新空間,所以相等
equals判斷的是值,所以2、4都是true