Android之UI界面的常見控件
1.TextView
TextView是文本視圖,只是用來顯示文字的。在Activity中顯示TextView, 要在對應的layout.xml文件去添加相應的控件標籤。這些xml標籤可以確定控件的位置,大小,顏色等屬性。
實例代碼:
<TextView
android:id="@+id/name_text_view"
android:layout_width="wrap_content"
android:layout_height="layout_height"
android:gravity="center"
android:textSize="30xp"
android:textColor="#ffffff"
android:text="bingo ">
</TextView>
屬性表述:
-
android:id屬性代表着TextView的Id,也就是TextView的唯一標示,在java代碼中我們可以通過findViewById()方法來通過Id獲取控件。
-
android:layout_width屬性代表着控件的寬度,該屬性的值是match_parent, 表示該控件的寬度與父視圖的寬度相同。
-
android:layout_height屬性代表着控件的高度,該屬性的值是wrap_content,表示控件的高度根據內容的高度進行改變。
-
android:gravity屬性代表着TextView中文字對齊方式,有多種方式
-
android:textSize屬性代表着TextView中文字的型號,也就是文字的大小。
-
android:textColor屬性設置的是TextView中文字的顏色,屬性值是16進制的色值。
-
android:text屬性就是用來設置TextView顯示的值的。
使用findViewById()方法通過id獲取上述控件,並獲取TextView中的值以及設置TextView中的值。具體代碼如下。
TextView myTextView = (TextView) findViewById(R.id.name_text_view);
String myText = myTextView.getText().toString();
myTextView.setText(myText+" Add");
2.Button
在Android中的按鈕就叫Button,添加Button,需要在Activity對應的佈局文件layout.xml中添加一個Button, 具體的xml代碼如下所示。
<Button
android:id="@+id/click_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="點我">
</Button>
在Activity的類中也是使用findViewById來通過Id獲取該按鈕,獲取按鈕後我們需要給按鈕綁定點擊事件。
button.setOnClickListener(this);
//重寫委託回調的方法
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.click_button:
//點擊按鈕後要做的事情
break;
default:
break;
}
}
3.EditText
Activity添加一個輸入框,在Android中輸入框的類型和標籤都是EditText。下方是其xml佈局方式.
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="placeHoder: type something here"
android:maxLines="6">
</EditText>
EditText標籤中比之前多了兩個屬性:
- android:hint屬性後邊是一個字符串,其實就是用來佔位用的字符串,功能是提示用戶該輸入框的作用
- android:macLines 用來設置輸入框的最大行數。
在Activity中獲取EditText對象,也是通過Id方式,下方代碼是獲取通過id實例化EditText對象,並獲取其中的文本在Toast上顯示。
EditText myEditText = (EditText) findViewById(R.id.edit_text);
String inputText = myEditText.getText().toString();
Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();
4.ImageView
爲Activity添一張圖片,運用ImageView。下方是其xml佈局方式:
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img_1">
</ImageView>
將以上控件顯示在頁面上,爲button綁定事件顯示圖片:
private EditText editText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.button);
editText = (EditText)findViewById(R.id.edit_text);
imageView = (ImageView)findViewById(R.id.image_view);
button.setOnClickListener((OnClickListener) this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.button:
imageView.setImageResource(R.drawable.img_2);
break;
default:
break;
}
}