Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 常用程式碼片段整理:剪貼簿、開啟瀏覽器、自訂 Dialog 等

編輯:關於 Android 程式設計

本文彙整幾段在 Android 開發中反覆用到的程式碼片段,涵蓋剪貼簿操作、呼叫瀏覽器、跳轉應用市集、Toast 持續顯示與自訂 Dialog,方便日後查閱。

一、複製與貼上

ClipboardManager clip =
        (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clip.setText("copy");   // 複製
clip.getText();         // 貼上

二、開啟瀏覽器

Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri content_url = Uri.parse("https://www.jb51.net");
intent.setData(content_url);
startActivity(intent);

// 若要指定特定瀏覽器,例如 UC:
// intent.setClassName("com.uc.browser", "com.uc.browser.ActivityUpdate");

三、依套件名稱前往應用市集搜尋

Intent intent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("market://search?q=pname:com.acp.main"));
startActivity(intent);

四、讓 Toast 持續顯示

Toast 本身是短暫提示,若真的需要延長顯示時間,可以搭配 Timer 反覆呼叫 show:

final Toast toast = Toast.makeText(context, "toast", Toast.LENGTH_LONG);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        while (flag) {
            toast.show();
        }
    }
}, 10);

不過這裡要誠實提醒:同一個 Toast 物件被反覆呼叫,系統只會依 queue 機制顯示,效果未必如預期;而無條件迴圈也會帶來資源消耗。實務上若需要長時間提示,Snackbar 或自訂的浮動元件是更合適的選擇。

五、自訂 Dialog

final Dialog mInfoDlg = new Dialog(context, R.style.dialog);
// R.style.dialog 用來移除 Dialog 上方的標題列

LayoutInflater factory = LayoutInflater.from(context);
View nCurrView = factory.inflate(R.layout.mydialog, null);
nCurrView.setBackgroundResource(R.drawable.bgline);

LinearLayout nParentLayout =
        (LinearLayout) nCurrView.findViewById(R.id.iparents);
nParentLayout.setBackgroundResource(R.drawable.titlebgline);

mInfoDlg.setContentView(nCurrView);

Button nBt1 = (Button) nCurrView.findViewById(R.id.button1);
nBt1.setText("返回");
nBt1.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
nBt1.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        mInfoDlg.dismiss();
    }
});

mInfoDlg.show();

styles.xml 中的 dialog 樣式:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="dialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowNoTitle">true</item>
    </style>
</resources>

titlebgline.xml 的圓角漸層背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#ff9911"
        android:endColor="#FF9911" />
    <stroke
        android:width="1dp"
        android:color="@color/inputTxt" />
    <corners android:radius="5dp" />
</shape>

以上片段多為日常開發的基礎工具,累積成自己的片段庫後,能省下不少翻文件的時間。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved