編輯:關於 Android 程式設計
入門 Android 開發,最先要熟悉的往往不是什麼架構模式,而是那些天天要用的基礎控件。本文把六組常用組件的布局屬性、事件監聽與運行效果整理在一起,方便對照練習。
先看布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- 單行顯示,超出部分中間省略 -->
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:ellipsize="middle"
android:singleLine="true"
android:text="我會開發android我會開發android我會開發android我會開發android" />
<!-- 文字陰影 -->
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:shadowColor="#0000ff"
android:shadowDx="15"
android:shadowDy="20"
android:shadowRadius="30"
android:text="我是陰影"
android:textColor="#dd0000"
android:textSize="20pt" />
<!-- 密碼輸入 -->
<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:password="true"
android:text="@string/hello_world" />
<!-- 左側帶圖標 -->
<TextView
android:id="@+id/textView4"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:drawableLeft="@drawable/ic_launcher"
android:text="@string/hello_world" />
<!-- 帶提示文案的輸入框 -->
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:cursorVisible="true"
android:hint="請輸入賬號"
android:textColorHint="#00dd00" />
<!-- 去掉背景的輸入框,適合多行意見反饋 -->
<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="@null"
android:hint="請輸入給我們的建議" />
</LinearLayout>
運行效果:
幾個值得記住的屬性:ellipsize 配合 singleLine 決定溢出文本的截斷方式(這裡是 middle,中間省略);shadowColor 系列四個屬性控制陰影顏色與偏移;drawableLeft 可以在文字左側掛一個 Drawable;android:background="@null" 則能把 EditText 默認的下劃線去掉,做純淨的多行輸入框時很好用。
布局文件:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕測試"
android:textSize="15pt" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#aaaaff"
android:shadowColor="#000000"
android:shadowDx="15"
android:shadowDy="20"
android:text="普通按鈕" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imgbutton_selector" />
</LinearLayout>
Activity 中的事件綁定:
public class MainActivity extends Activity {
private Button btn = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 透過 findViewById 取得按鈕實例
btn = (Button) findViewById(R.id.button1);
// 用匿名內部類設置監聽器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "你點擊了普通按鈕", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
運行效果:
要留意 Button 與 ImageButton 引用圖片的方式不同:ImageButton 用 background 時圖片會被拉伸鋪滿,用 src 則會按比例居中顯示。想要多狀態切換效果,把 src 指向一個 selector 即可,比如上面的 imgbutton_selector。
xml 布局文件:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="單選復選測試"
android:textSize="12pt" />
<RadioGroup
android:id="@+id/rg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:layout_width="50dp"
android:layout_height="50dp"
android:text="男" />
<RadioButton
android:layout_width="50dp"
android:layout_height="50dp"
android:text="女" />
</RadioGroup>
<CheckBox
android:id="@+id/cbmale"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="學生" />
<CheckBox
android:id="@+id/cbfemale"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="20歲" />
</LinearLayout>
Activity 代碼:
public class MainActivity extends Activity {
private CheckBox checkBoxMale;
private CheckBox checkBoxFemale;
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBoxMale = (CheckBox) findViewById(R.id.cbmale);
checkBoxFemale = (CheckBox) findViewById(R.id.cbfemale);
radioGroup = (RadioGroup) findViewById(R.id.rg);
// 單個 CheckBox 各自監聽
checkBoxMale.setOnCheckedChangeListener(new MyCheckListener());
checkBoxFemale.setOnCheckedChangeListener(new MyCheckListener());
// RadioGroup 由分組統一監聽
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(MainActivity.this,
"你選中了" + ((RadioButton) findViewById(group.getCheckedRadioButtonId())).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
// 實現 CompoundButton.OnCheckedChangeListener
// 注意:這個接口與 RadioGroup 那個同名,但所在的類不同
class MyCheckListener implements android.widget.CompoundButton.OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// 別忘了調用 show(),只 new 不 show 是不會彈的
Toast.makeText(MainActivity.this, "你選擇了" + buttonView.getText(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "你取消選擇了" + buttonView.getText(),
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
運行效果:
這一組最容易踩的兩個坑:一是 OnCheckedChangeListener 有兩個同名版本,RadioGroup 的監聽粒度是「整組」,CompoundButton 的監聽粒度是「單個控件」,import 時務必看清包名;二是 Toast 必須調用 show() 才會顯示。
ToggleButton 相當於一個自帶開關樣式的按鈕,用 textOn 和 textOff 分別指定兩種狀態下的顯示文字。用它來做登錄/注冊界面切換非常合適。
xml 文件:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="狀態按鈕測試"
android:textSize="12pt" />
<ToggleButton
android:id="@+id/tButton"
android:layout_width="100dp"
android:layout_height="40dp"
android:checked="true"
android:textOff="登錄界面"
android:textOn="注冊界面" />
<RelativeLayout
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是登錄界面"
android:textSize="20pt" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是注冊界面"
android:textSize="20pt" />
</RelativeLayout>
</LinearLayout>
Activity:
public class MainActivity extends Activity {
private ToggleButton tButton;
private RelativeLayout login;
private RelativeLayout register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tButton = (ToggleButton) findViewById(R.id.tButton);
login = (RelativeLayout) findViewById(R.id.login);
register = (RelativeLayout) findViewById(R.id.register);
tButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
login.setVisibility(View.VISIBLE);
register.setVisibility(View.INVISIBLE);
} else {
login.setVisibility(View.INVISIBLE);
register.setVisibility(View.VISIBLE);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
運行效果:
順帶說一下 INVISIBLE 和 GONE 的區別,這裡特意用的是前者:INVISIBLE 只是不可見,仍佔據原來的位置;GONE 則連位置都不佔。切換登錄/注冊時用 INVISIBLE,兩個界面的高度不會跳變,體驗更平穩。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android中的時間"
android:textSize="12pt" />
<DigitalClock
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_centerVertical="true" />
</RelativeLayout>
效果圖:
這兩個控件都是系統內置的,直接放進布局就能自動走時,無需任何代碼。AnalogClock 是模擬時鐘,DigitalClock 是數字時鐘(DigitalClock 在較新版本中已被標記為過時,新項目可考慮用 TextClock 替代)。
xml 文件:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="60dp"
android:background="#ffffff" />
<Button
android:id="@+id/low"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="low alpha" />
<Button
android:id="@+id/high"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/low"
android:text="high alpha" />
<Button
android:id="@+id/nextImage"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/high"
android:text="next image" />
</RelativeLayout>
Activity 代碼:
public class MainActivity extends Activity {
private ImageView imageView;
private Button lowButton;
private Button highButton;
private Button nextImageButton;
// 圖片資源數組
private int[] images = new int[]{
R.drawable.image1, R.drawable.image2,
R.drawable.image3, R.drawable.image4,
};
private int currentImage = 2; // 初始顯示的圖片下標
private int alpha = 255; // 初始透明度
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image);
lowButton = (Button) findViewById(R.id.low);
highButton = (Button) findViewById(R.id.high);
nextImageButton = (Button) findViewById(R.id.nextImage);
imageView.setImageResource(images[currentImage]);
// 切換下一張圖片
nextImageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (++currentImage > 3) {
currentImage = 0;
}
imageView.setImageResource(images[currentImage]);
}
});
// 調整透明度
lowButton.setOnClickListener(new MyListener());
highButton.setOnClickListener(new MyListener());
}
class MyListener implements OnClickListener {
@Override
public void onClick(View v) {
if (v == lowButton) alpha -= 50;
if (v == highButton) alpha += 50;
if (alpha <= 0) alpha = 0;
if (alpha >= 255) alpha = 255;
imageView.setImageAlpha(alpha);
System.out.println(alpha);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
效果圖:
這個例子演示了 ImageView 的兩個核心操作:setImageResource() 換圖,setImageAlpha() 調透明度(取值 0 到 255,0 全透明)。透明度邊界判斷那兩行不能省,否則很快會超出有效範圍。
第一,屬性先看效果再查文檔。像 ellipsize、shadowDx、drawableLeft 這些,改一個值跑一次,比讀十遍文檔印象更深。
第二,監聽器要看清類別。同名接口在不同類下語義完全不同,RadioGroup 與 CompoundButton 就是最典型的例子。
第三,把 Toast、findViewById、setOnClickListener 這三件套寫熟。它們幾乎出現在每一個 Activity 裡,肌肉記憶一旦建立,後面寫自定義 View、寫 Adapter 都會輕鬆很多。
第四,注意 RelativeLayout 的定位屬性組合,比如 layout_toRightOf 加 layout_alignParentBottom 就能實現一排底部對齊的按鈕,這類組合技巧在沒有 ConstraintLayout 的年代是必備技能。
Android 進程間通訊入門:Binder 機制概覽
Android 應用通常由多個 Activity 與 Service 組成,這些元件可能位於同一個行程,也可能分散在不同行程。當行程不同時,就需要依靠行程間通訊機制交換資
Android 自定義 Material 風格環形進度條
本文介紹如何自定義一個 Material 風格的環形進度條 CircleProgressBar,先看效果: 布局文件 在布局中直接使用自定義 View,並通過自定義屬
Android 高仿 QQ 5.2 雙向側滑菜單 DrawerLayout 實作
DrawerLayout 很適合用來實作左右側滑選單。若要模擬 QQ 風格的雙向菜單,可將 DrawerLayout 作為根配置,第一個子檢視放內容,第二個放左側選單,第
Android 入門:四種 UI 布局構建方式完整梳理
一句話開場 使用者打開一個 App 的第一眼,看到的就是介面。簡潔、順眼、操作直覺的 UI,往往能迅速贏得認可;而凌亂擁擠的畫面,再強的功能也很難被發現。所以寫 Andr