編輯:關於 Android 程式設計
寫 Android 久了就會發現,真正拉開介面體驗差距的往往不是基礎的 TextView 和 Button,而是那些「會排、會滑、會翻頁」的進階控制元件。這一篇整理幾個高頻出現的傢伙,並用可以跑起來的範例把它們串成一個完整的閱讀類 App 骨架。
做介面時,按下的高亮效果與圓角邊框幾乎一定會用到。先寫一個 selector 管理文字顏色狀態:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:color="#fc03" android:state_pressed="true"/>
<item android:color="#09090a"/>
</selector>
再寫一個 shape 做圓角加描邊的背景:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<stroke android:color="#f50202" android:width="1dp"/>
<corners android:radius="9dp"/>
</shape>

設定頁是 ScrollView 最典型的舞臺。記住一個鐵律:ScrollView 只能有一個直接子容器,所以我們在外層放一個 LinearLayout 包住所有內容,再一條條塞進去。下面這段版面每個設定項都是「文字 + 右側控制項」的橫向排列,中間用 1dp 的 View 當分隔線:
<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="com.example.jreduch7292.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- 標題列:圖示 + 設置 + 意見反饋 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/fnl"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:text="設置"
android:textSize="30sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="意見反饋"
android:textSize="30sp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#565454"/>
<!-- 列表顯示摘要:一個 CheckBox -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="列表顯示摘要"
android:textSize="30sp"/>
<CheckBox
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="150dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#565454"/>
<!-- 字體大小:目前值 + 箭頭,點擊後可再跳一層 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="字體大小"
android:textSize="30sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="190dp"
android:text="中"
android:textSize="30sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/fhe2"/>
</LinearLayout>
<!-- 此處省略「列表頁評論 / 2G-3G 流量 / 清理緩存」等結構完全相同的項目 -->
<!-- 推送通知、互動插件、自動優化閱讀:預設勾選的 CheckBox -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="推送通知"
android:textSize="30sp"/>
<CheckBox
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="200dp"
android:checked="true"/>
</LinearLayout>
<!-- 收藏時轉發、頂踩時轉發等,寫法同上 -->
</LinearLayout>
</ScrollView>
</RelativeLayout>

可以看到,這類頁面的重複度極高。真正在專案裡,通常會抽一個 <include> 或自訂 View 來收斂,而不是硬寫十幾段一樣的 LinearLayout。

GridView 本身只負責排布,資料與呈現要靠 Adapter。最省事的是 SimpleAdapter,它要求資料源是一組 Map:
package com.example.jreduch7292;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GridViewActivity extends AppCompatActivity {
private GridView gv;
private ImageView big;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gv = (GridView) findViewById(R.id.gv);
big = (ImageView) findViewById(R.id.big);
final List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("img", R.mipmap.a);
map.put("name", "字母A");
list.add(map);
map = new HashMap<>();
map.put("img", R.mipmap.b);
map.put("name", "字母B");
list.add(map);
// C ~ H 依此類推,每格都是「一張圖 + 一個名稱」
/*
* SimpleAdapter 的三個要點:
* 1. 資料源必須是 Map 的集合(實現 Map 接口)
* 2. from 指向資料源 Map 中的鍵
* 3. to 負責把值塞進版面對應控件的 id
*/
SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.grid_layout,
new String[]{"img", "name"},
new int[]{R.id.iv, R.id.tv});
gv.setAdapter(sa);
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String, Object> map = (Map<String, Object>) list.get(position);
Toast.makeText(getBaseContext(), "" + map.get("name"), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), BigActivity.class);
intent.putExtra("img", (int) map.get("img"));
startActivity(intent);
}
});
}
}
對應的 GridView 版面,這裡幾個屬性值得記住:numColumns 決定每行幾格,stretchMode 決定多餘空間怎麼分,listSelector 與 cacheColorHint 設成透明可以去掉預設的高亮與底色。
<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="com.example.jreduch7292.GridViewActivity">
<GridView
android:id="@+id/gv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:columnWidth="100dp"
android:horizontalSpacing="5dp"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:scrollbars="none"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"/>
</RelativeLayout>
每一格的版面則是「圖 + 字」。這裡的 scaleType="centerCrop" 是等比縮放並裁切填滿,圖片牆不會變形就靠它:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="測試"/>
</LinearLayout>

點擊縮圖後跳轉大圖頁,是圖片類應用的標配。這裡用第三方的 PhotoView 承載圖片,順手加一段旋轉屬性動畫讓場景不生硬:
package com.example.jreduch7292;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.BounceInterpolator;
import uk.co.senab.photoview.PhotoView;
public class BigActivity extends AppCompatActivity {
private PhotoView big;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_big);
big = (PhotoView) findViewById(R.id.big);
Intent intent = getIntent();
int imgId = intent.getIntExtra("img", R.mipmap.ic_launcher);
big.setImageResource(imgId);
// 屬性動畫:0 到 360 度旋轉,並套用回彈插補器
ObjectAnimator oja = ObjectAnimator.ofFloat(big, "rotation", 0, 360);
oja.setDuration(3000);
oja.setRepeatCount(0);
oja.setInterpolator(new BounceInterpolator());
oja.start();
}
}
<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="com.example.jreduch7292.BigActivity">
<uk.co.senab.photoview.PhotoView
android:id="@+id/big"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

GridView 並不一定用來放圖。新聞 App 頂部的「我的頻道」就是一個四列的純文字網格,用 Button 加上圓角背景當格子,觸感更接近標籤:
package com.example.jreduch7292;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GridViewTextActivityr extends AppCompatActivity {
private GridView gv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view_text_activityr);
getSupportActionBar().hide(); // 隱藏標題列
gv1 = (GridView) findViewById(R.id.gv1);
final List<Map<String, Object>> list = new ArrayList<>();
String[] channels = {"推薦", "熱點", "體育", "煙台", "視頻", "汽車", "訂閱",
"社會", "財經", "科技", "健康", "軍事", "彩票", "國際", "段子"};
for (String name : channels) {
Map<String, Object> map = new HashMap<>();
map.put("name", name);
list.add(map);
}
SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.grid2_layout,
new String[]{"name"}, new int[]{R.id.tv});
gv1.setAdapter(sa);
}
}
版面部分,「我的頻道」標題旁邊有一顆編輯鈕,背景就是前面寫的 shape:
<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="com.example.jreduch7292.GridViewTextActivityr">
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#b3a9a9"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我的頻道"
android:textSize="30dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:background="@drawable/bian"
android:text="編輯"
android:textColor="#f70808"
android:textSize="25sp"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:src="@mipmap/fhee"/>
</LinearLayout>
<GridView
android:id="@+id/gv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/ll"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:columnWidth="100dp"
android:horizontalSpacing="5dp"
android:listSelector="#00000000"
android:numColumns="4"
android:scrollbars="none"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"/>
</RelativeLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/biankuan"
android:textColor="@color/red"
android:textSize="20dp"/>
</LinearLayout>

這一節是整篇的核心。做法是:ViewPager 負責翻頁,HorizontalScrollView 裡的 RadioGroup 負責頂部的頁籤,兩邊透過監聽器雙向同步。滑到第三頁,第三個單選鈕自動亮起;點第五個單選鈕,ViewPager 自動切到第四頁。
package com.example.jreduch7292;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.example.jreduch7292.adapter.MyViewPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ScrollViewActivity extends AppCompatActivity {
private RadioGroup rg;
private ViewPager vp;
private List<ImageView> imgList;
private MyViewPagerAdapter mp;
private HorizontalScrollView hs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_view);
hs = (HorizontalScrollView) findViewById(R.id.hs);
rg = (RadioGroup) findViewById(R.id.rg);
vp = (ViewPager) findViewById(R.id.vp);
vpInit();
// 點頁籤 -> 換頁
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb1:
vp.setCurrentItem(0);
Toast.makeText(getBaseContext(), "推薦1", Toast.LENGTH_SHORT).show();
break;
case R.id.rb2:
vp.setCurrentItem(1);
Toast.makeText(getBaseContext(), "推薦2", Toast.LENGTH_SHORT).show();
break;
case R.id.rb3:
vp.setCurrentItem(2);
Toast.makeText(getBaseContext(), "推薦3", Toast.LENGTH_SHORT).show();
break;
case R.id.rb4:
vp.setCurrentItem(3);
break;
case R.id.rb5:
vp.setCurrentItem(4);
break;
default:
break;
}
}
});
}
public void vpInit() {
imgList = new ArrayList<>();
int[] resIds = {R.mipmap.zyfzyf, R.mipmap.eet, R.mipmap.eer, R.mipmap.eep, R.mipmap.eeq,
R.mipmap.eew, R.mipmap.eex, R.mipmap.eez, R.mipmap.efa, R.mipmap.efb};
for (int resId : resIds) {
ImageView iv = new ImageView(this);
iv.setImageResource(resId);
imgList.add(iv);
}
mp = new MyViewPagerAdapter(imgList);
vp.setAdapter(mp);
vp.setCurrentItem(0);
// 換頁 -> 同步頁籤
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
RadioButton rb = (RadioButton) rg.getChildAt(position);
if (rb != null) {
rb.setChecked(true);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
頁籤為什麼要放在 HorizontalScrollView 裡?因為頻道數量可能超過螢幕寬度,這時候還能橫向滑動切換,體驗才完整。android:button="@null" 這一行是去掉單選鈕預設的小圓點。
<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="com.example.jreduch7292.ScrollViewActivity">
<HorizontalScrollView
android:id="@+id/hs"
android:layout_width="match_parent"
android:layout_height="50dp"
android:scrollbars="none">
<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb1"
android:layout_width="50dp"
android:layout_height="match_parent"
android:button="@null"
android:checked="true"
android:gravity="center"
android:text="推薦1"
android:textColor="@color/rdbt_text_color"/>
<!-- rb2 ~ rb10 屬性完全一致,只換 id 與 text -->
</RadioGroup>
</HorizontalScrollView>
</RelativeLayout>

如果只是想讓使用者從幾個選項裡挑一個,Spinner 比自建彈窗省事太多。它有兩種資料來源:直接寫在 strings.xml 的陣列,或在程式碼裡塞 ArrayAdapter。
package com.example.jreduch7292;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class SpinnerActivity extends AppCompatActivity {
private Spinner sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
sp = (Spinner) findViewById(R.id.sp);
List<String> cityList = new ArrayList<>();
cityList.add("北京");
cityList.add("上海");
cityList.add("廣州");
// 系統自帶的最簡單樣式,只顯示一行文字
ArrayAdapter aa = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, android.R.id.text1, cityList);
sp.setAdapter(aa);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),
sp.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
版面同時示範了兩種寫法:上面那顆用 android:entries 直接關聯資源陣列,下面那顆由程式碼動態指定 Adapter。
<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="com.example.jreduch7292.SpinnerActivity">
<Spinner
android:id="@+id/sp1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/city"/>
<Spinner
android:id="@+id/sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/sp1"/>
</RelativeLayout>
<resources>
<string-array name="city">
<item>煙台</item>
<item>濟南</item>
<item>青島</item>
</string-array>
</resources>

這幾個元件其實共用同一套思路:控制元件負責容器與排布,Adapter 負責資料到 view 的映射。把這層關係想通,GridView、ListView、Spinner、ViewPager 之間就能自由切換。下篇再來談側邊欄 SlideMenu 與下拉刷新。
深入解析 Android Studio 專案的組成結構
原文鏈接 專案總覽 在 Android Studio 中,一個專案囊括了某支 App 所需的全部內容:原始碼、相依資源、測試程式碼,以及各項 build 組態。當你建立一
Android 教學:實現螢幕自適應方向、尺寸與解析度的方法
本文透過實例,講解 Android 開發中如何實現螢幕自適應方向、尺寸與解析度,涵蓋介面佈局、多解析度支援、取得螢幕尺寸、橫向與直向切換等常見主題,分享給大家參考。螢幕介
美團 Android DEX 自動拆包與動態加載實踐全解析
問題的起點 對 Android 開發者而言,隨著業務規模不斷擴張,新功能與新類庫層出不窮,程式碼急遽膨脹,APK 體積也水漲船高。終有一天,你會迎面撞上這類錯誤: 打包
我的第一個 Android 項目:偽即時通訊 DemoChat 開發全記錄
學習 Android 到現在大概還不到一個月,我很激動能憑自己的努力與鑽研,做出一個自己想要的 App。雖然它功能還不完善、界面頗為樸素、Bug 也不少,但這畢竟是我親手