編輯:關於 Android 程式設計
開篇先介紹幾個放在眼前卻常被忽略的快捷鍵,它們能充分展現 Android Studio 強大的搜索能力,大幅提升大工程的開發維護效率。
雙擊 Shift:喚出 Search Everywhere,全局搜索。


Ctrl+Shift+N:根據文件名打開文件。

Ctrl+E:打開最近文件。

Alt+Home:定位導航欄。

本篇重點介紹 Google 推薦使用的 Fragment,以及它與 Activity 的通信方式。
新建一個 BlankFragment:

IDE 自動生成的代碼如下:
package com.hitsz.xiaokai.fragmentcom;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link BlankFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link BlankFragment#newInstance} factory method to create an instance of this fragment.
* 實現子 Fragment 需要繼承 Fragment,這是 Google 推薦的模板:在 Fragment 裡定義一個接口,
* 依附它的 Activity 必須實現這個接口來完成相應的交互事件;Fragment 本身則使用工廠方法創建實例。
*/
public class BlankFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of this fragment using the provided parameters.
*/
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 加載特定布局文件到布局容器中
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// 判斷 activity 是否實現了內部接口,沒有實現則拋出異常
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
// 解除依附關係,同時將接口對象置空,方便垃圾回收
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this fragment
* to allow an interaction in this fragment to be communicated to the activity.
* 此接口必須被 activity 實現
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}

布局文件 layout/article_view.xml:
layout/news_articles.xml:
<framelayout
android:id="@+id/fragment_container"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android">
</framelayout>
layout_large/news_articles.xml(大屏時可用雙欄布局):
<framelayout
android:id="@+id/fragment_container"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android">
</framelayout>
顯示數據的 Ipsum.java:
package com.hitsz.xiaokai.fragmentcom;
public class Ipsum {
static String[] Headlines = {"Article One", "Article Two"};
static String[] Articles = {
"Article One\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub...",
"Article Two\n\nVinyl williamsburg non velit, master cleanse four loko banh mi..."
};
}
導航 Fragment,繼承自 ListFragment,自帶 ListView:
HeadlinesFragment.java:
package com.hitsz.xiaokai.fragmentcom;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// 容器 Activity 必須實現此接口,Fragment 才能投遞消息
public interface OnHeadlineSelectedListener {
// 當點擊 list item 時回調,攜帶點擊位置信息
public void onArticleSelected(int position);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 為 Honeycomb 及以上版本使用不同的 list item 布局
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
// 用 Ipsum 的 headlines 數組創建適配器顯示 listview
setListAdapter(new ArrayAdapter(getActivity(), layout, Ipsum.Headlines));
}
@Override
public void onStart() {
super.onStart();
// 雙欄布局時,設置 listview 高亮選中項
if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// 確保依附的 activity 實現了回調接口,否則拋出異常
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// 通知 activity 選中的 item
mCallback.onArticleSelected(position);
// 設為高亮
getListView().setItemChecked(position, true);
}
}
顯示詳細內容的 ArticleFragment.java:
package com.hitsz.xiaokai.fragmentcom;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ArticleFragment extends Fragment {
// Fragment 通信參數
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// 考慮 activity 非正常退出(如旋轉屏幕),還原狀態
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
return inflater.inflate(R.layout.article_view, container, false);
}
@Override
public void onStart() {
super.onStart();
// onStart 時布局已應用,可安全地設置文章文本
Bundle args = getArguments();
if (args != null) {
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
updateArticleView(mCurrentPosition);
}
}
public void updateArticleView(int position) {
TextView article = (TextView) getActivity().findViewById(R.id.article);
article.setText(Ipsum.Articles[position]);
mCurrentPosition = position;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// 保存當前文章選擇,以防 Fragment 重建
outState.putInt(ARG_POSITION, mCurrentPosition);
}
}
主 Activity,MainActivity.java:
package com.hitsz.xiaokai.fragmentcom;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
// 實現需要通信的 Fragment 內部接口
public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnHeadlineSelectedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
// 若布局使用 fragment_container FrameLayout,需用 Fragment 事務加載第一個 Fragment
if (findViewById(R.id.fragment_container") != null) {
// 若從之前狀態恢復,則直接返回,避免 Fragment 重疊
if (savedInstanceState != null) {
return;
}
HeadlinesFragment firstFragment = new HeadlinesFragment();
firstFragment.setArguments(getIntent().getExtras());
// 把 Fragment 添加到 fragment_container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
public void onArticleSelected(int position) {
// 從 activity 布局中取出 article fragment
ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// 雙欄布局:直接調用 ArticleFragment 的方法更新內容
articleFrag.updateArticleView(position);
} else {
// 單欄布局:需要替換 Fragment
ArticleFragment newFragment = new ArticleFragment();
// 通過 Bundle 攜帶數據,實現 Fragment 之間的通信
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// 用新 Fragment 替換 fragment_container,並加入返回棧
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
運行效果:


動手做一個 Android 驗證碼控件:自定義 View 全流程實踐
本文在鴻洋大神《Android 自定義 View(一)》的基礎上做了擴展,同時也整理了不少關於自定義 View 構造函數的細節,適合剛入門自定義控件的同學當作一份完整練手
IIS 怎麼加上自訂 MIME 類型?以 apk、ipa 為例
在 IIS 7 中,預設的 MIME 類型並不包含所有的副檔名,像是現在很常見的 apk、ipa 安裝檔,都需要手動補上,否則用戶下載時可能會遇到無法正確處理的問題。 具
Android 完全退出應用程式的實作方式
在 Android 中,若要完全退出應用程式,不能只依賴單一 Activity 的 finish。若 App 內有多個 Activity,直接呼叫 killProcess
Android Studio 多渠道批量打包與代碼混淆實踐
一、批量打包 1. 專案已整合友盟統計,並在 AndroidManifest.xml 中加入: <meta-data android:name=UMENG_CHA