# 常用控件
## 1.文本類控件TextView
TextView是 Android 程序開發中最常用的控件之一,主要功能是向用戶展示文本的內容,它是不可編輯的 ,只能通過初始化設置或在程序中修改。
### 屬性:
```
//文本文字
android:text="@string/hello_world" //兩種方式,直接具體文本或者引用values下面的string.xml里面的元素
//字體大小
android:textSize="24sp" //以sp為單位
//字體顏色
android:textColor="#0000FF" //RGB顏色
//字體格式
android:textStyle="normal" //normal,bold,italic分別為正常,加粗以及斜體,默認為normal
//文本顯示位置
android:gravity="center" //來指定文字的對齊方式,可選值有 top、bottom、left、right、center 等
//是否只在一行內顯示全部內容
android:singleLine="true" //true或者false,默認為false
```
## 2. 文本類控件EditText
相比TextView, EditText是可以編輯的,可以用來與用戶進行交互,其用法和TextView也是類似的
### 屬性:
```
//文本文字
android:text="@string/hello_world" //兩種方式,直接具體文本或者引用values下面的string.xml里面的元素
//文本提示內容
android:hint="hello_world" //android:text和android:hint區別是后者只是提示作用,真正需要輸入的時候提示的內容會消失
//字體大小
android:textSize="24sp" //以sp為單位
//字體顏色
android:textColor="#0000FF" //RGB顏色
//字體格式
android:textStyle="normal" //normal,bold,italic分別為正常,加粗以及斜體,默認為normal
//文本顯示位置
android:gravity="center" //來指定文字的對齊方式,可選值有 top、bottom、left、right、center 等
//是否只在一行內顯示全部內容
android:singleLine="true" //true或者false,默認為false
//輸入內容設置為password類型
android:password="true" //輸入的內容會變成······
//輸入內容設置為phoneNumber類型
android:phoneNumber="true" //只能輸入數字
//設定光標為顯示/隱藏
android:cursorVisible = "false" //true或者false,默認為true顯示
```
### 在Activity中使用
```
public class MainActivity extends Activity {
//聲明一個EditText
private EditText edittext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//給當前的活動加載一個布局
setContentView(R.layout.activity_main);
//初始化edittext
edittext=(EditText) findViewById(R.id.edit_text);
}
...
...
//在方法中調用給edittext賦值
edittext.setText("success");
...
...
}
```
## 3. 按鈕類控件Button
Button控件也是使用過程中用的最多的控件之一,所以需要好好掌握。用戶可以通過單擊 Button 來觸發一系列事件,然后為 Button 注冊監聽器,來實現 Button 的監聽事件。
### 屬性:
```
//按鈕上顯示的文字
android:text="theButton" //兩種方式,直接具體文本或者引用values下面的string.xml里面的元素@string/button
//按鈕字體大小
android:textSize="24sp" //以sp為單位
//字體顏色
android:textColor="#0000FF" //RGB顏色
//字體格式
android:textStyle="normal" //normal,bold,italic分別為正常,加粗以及斜體,默認為normal
//是否只在一行內顯示全部內容
android:singleLine="true" //true或者false,默認為false
```
### 在Activity中使用
```
public class MainActivity extends Activity {
private EditText edittext;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext=(EditText) findViewById(R.id.edit_text);
button = (Button) findViewById(R.id.button);
//為button按鈕注冊監聽器,并通過匿名內部類實現
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//點擊Button會改變edittext的文字為"點擊了Button"
edittext.setText("點擊了Button");
}
});
}
}
```