コンテンツ作成 > アプリ > ユーティリティ

ユーティリティ


コンテンツ


概要

  • このページに記載されているすべてのソースコードはパブリックドメインとします
    • 内容は無保証です

罫線付きのEditTextクラス

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * 罫線付きEditTextクラスです。<br>
 */
public class RuledEditText extends EditText
{
    /** 罫線の色 */
    private static final int RULE_COLOR = Color.rgb(200, 200, 200);

    /** Paint */
    private Paint mPaint;

    /**
     * コンストラクタです。<br>
     *
     * @param context
     *            コンテキスト
     */
    public RuledEditText(Context context)
    {
        super(context);

        // フィールドの初期化
        init();
    }

    /**
     * コンストラクタです。<br>
     *
     * @param context
     *            コンテキスト
     * @param attrs
     *            属性セット
     */
    public RuledEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        // フィールドの初期化
        init();
    }

    /**
     * コンストラクタです。<br>
     *
     * @param context
     *            コンテキスト
     * @param attrs
     *            属性セット
     * @param defStyle
     *            スタイル
     */
    public RuledEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);

        // フィールドの初期化
        init();
    }

    /**
     * フィールドの初期化処理です。<br>
     */
    private void init()
    {
        // Paintを生成
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(RULE_COLOR);
        mPaint.setAntiAlias(false);
        mPaint.setStrokeWidth(0);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onDraw(Canvas canvas)
    {
        try
        {
            // 左右パティングを取得
            final int left = getTotalPaddingLeft();
            final int right = getMeasuredWidth() - getTotalPaddingRight();

            // 線を引ける場合
            if(left < right)
            {
                // 描画する行数を計算
                final int lineHeight = getLineHeight();
                final int lineCount = Math.max(getMeasuredHeight() / lineHeight, getLineCount());

                // 2行以上ある場合
                if(lineCount > 1)
                {
                    // 描画座標の設定
                    final float[] pts = new float[(lineCount - 1) << 2];
                    int index = 0;
                    int y = lineHeight + getTotalPaddingTop() + 1;

                    for(int i = 1; i < lineCount; i++)
                    {
                        // 座標を詰める
                        pts[index] = left;
                        pts[index + 1] = y;
                        pts[index + 2] = right;
                        pts[index + 3] = y;

                        index += 4;
                        y += lineHeight;
                    }

                    // 線の描画
                    canvas.drawLines(pts, mPaint);
                }
            }
        }
        catch(Exception e)
        {
            // 例外を握りつぶす
        }

        // 親クラスの描画
        super.onDraw(canvas);
    }
}

現在のアプリをGoogle Playを開く

    /**
     * Google Playを開きます。
     *
     * @param context コンテキスト
     */
    public static void showGooglePlay(Context context)
    {
        // Intentを生成
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // インテントを投げる
        try
        {
            context.startActivity(intent);
        }
        catch(Exception e)
        {
        }
    }

現在のアプリを共有する

    /**
     * アプリを共有します。
     *
     * @param context コンテキスト
     * @param appName アプリ名のリソースID
     */
    public static void shareThisApp(Context context, int appName)
    {
        // アプリ名を取得
        String app = context.getString(appName);

        // パッケージ名を取得
        String pkg = context.getPackageName();

        // Intentを生成
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, app + " https://play.google.com/store/apps/details?id=" + pkg + " ");

        // Intentを投げる
        try
        {
            context.startActivity(intent);
        }
        catch(Exception e)
        {
        }
    }

インストール先クラス

  • リフレクションを使ってインストール先を取得する
  • SD移動はAndroid 2.2以降だがこのクラスでの判定はAndroid2.1以前でも使用可能
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;

/**
 * インストール先クラス
 */
public final class InstallLocation
{
    /** インストール先(自動) */
    public static final int INSTALL_LOCATION_AUTO;
    /** インストール先(内部メモリのみ) */
    public static final int INSTALL_LOCATION_INTERNAL_ONLY;
    /** インストール先(外部メモリ優先) */
    public static final int INSTALL_LOCATION_PREFER_EXTERNAL;
    /** インストール先(未指定) */
    public static final int INSTALL_LOCATION_UNSPECIFIED;
    /** インストール先(未サポート) */
    public static final int INSTALL_LOCATION_UNSUPPORTED = -1;
    
    /** 外部ストレージフラグ */
    public static final int FLAG_EXTERNAL_STORAGE;
    
    // 利用可否フラグ
    private static final boolean mIsAvailable;
    
    // ApplicationInfoを優先するかのフラグ
    private static final boolean mIsAppInfo;
    
    // コンストラクタ
    private InstallLocation()
    {
    }
    
    // 静的初期化子
    static
    {
        // 変数の初期化
        int auto = 0;
        int internal_only = 0;
        int prefer_external = 0;
        int unspecified = 0;
        int external_storage = 0;
        boolean isAvailable = false;
        boolean isAppInfo = false;
        
        try
        {
            // 各フィールドをリフレクションで読み出す
            auto = PackageInfo.class.getField("INSTALL_LOCATION_AUTO").getInt(PackageInfo.class);
            internal_only = PackageInfo.class.getField("INSTALL_LOCATION_INTERNAL_ONLY").getInt(PackageInfo.class);
            prefer_external = PackageInfo.class.getField("INSTALL_LOCATION_PREFER_EXTERNAL").getInt(PackageInfo.class);
            unspecified = PackageInfo.class.getField("INSTALL_LOCATION_UNSPECIFIED").getInt(PackageInfo.class);
            external_storage = ApplicationInfo.class.getField("FLAG_EXTERNAL_STORAGE").getInt(ApplicationInfo.class);
            
            // すべて読み出せた場合はtrue
            isAvailable = true;
        }
        catch(Exception e)
        {
        }
        
        try
        {
            // ApplicationInfo.installLocationをリフレクションで読み出す
            ApplicationInfo.class.getField("installLocation");
            
            // 存在した場合はApplicationInfoのフィールドを使う
            isAppInfo = true;
        }
        catch(Exception e)
        {
        }
        
        // 定数に格納
        INSTALL_LOCATION_AUTO = auto;
        INSTALL_LOCATION_INTERNAL_ONLY = internal_only;
        INSTALL_LOCATION_PREFER_EXTERNAL = prefer_external;
        INSTALL_LOCATION_UNSPECIFIED = unspecified;
        FLAG_EXTERNAL_STORAGE = external_storage;
        mIsAvailable = isAvailable;
        mIsAppInfo = isAppInfo;
    }
    
    /**
     * インストール先取得を取得します。
     * 
     * @param pkg パッケージ情報を指定します。
     * @param app アプリケーション情報を指定します。
     * @return インストール先を返します。
     */
    public static int getInstallLocation(PackageInfo pkg, ApplicationInfo app)
    {
        // 使用不可の場合
        if(!mIsAvailable)
        {
            return INSTALL_LOCATION_UNSUPPORTED;
        }
        
        int res = INSTALL_LOCATION_UNSUPPORTED;
        
        // ApplicationInfoを優先する場合
        if(mIsAppInfo)
        {
            try
            {
                // ApplicationInfo.installLocationを取得
                res = ApplicationInfo.class.getField("installLocation").getInt(app);
            }
            catch(Exception e)
            {
            }
        }
        else
        {
            try
            {
                // PackageInfo.installLocationを取得
                res = PackageInfo.class.getField("installLocation").getInt(pkg);
            }
            catch(Exception e)
            {
            }
        }

        return res;
    }
}

マッシュルームのラッパークラス

  • Simejiで利用できるマッシュルームのラッパークラス
import android.app.Activity;
import android.content.Intent;

/*
<intent-filter>
<action android:name="com.adamrocker.android.simeji.ACTION_INTERCEPT"></action>
<category android:name="com.adamrocker.android.simeji.REPLACE"></category>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
*/

/**
 * マッシュルームラッパークラス
 */
public final class Mushroom
{
    // Action定数
    private static final String ACTION_INTERCEPT = "com.adamrocker.android.simeji.ACTION_INTERCEPT";

    // Extra定数
    private static final String EXTRA_REPLACE_KEY = "replace_key";

    // コンストラクタ
    private Mushroom()
    {
    }
    
    /**
     * マッシュルームに対応したIntentを持っているか調べます。
     * 
     * @param activity 対象のActivityを指定します。
     * @return マッシュルーム対応ならtrue、そうでない場合はfalseを返します。
     */
    public static boolean hasMushroomIntent(Activity activity)
    {
        // Intentを取得
        Intent intent = activity.getIntent();
        
        // Intentがnullの場合
        if(intent == null)
        {
            return false;
        }
        
        // Actionを取得        
        String action = intent.getAction();
        
        // Actionがnullの場合
        if(action == null)
        {
            return false;
        }
        
        // Actionが一致しない場合
        if(!action.equals(ACTION_INTERCEPT))
        {
            return false;
        }
        
        return true;
    }

    /**
     * 置換前文字列を取得します。
     * 
     * @param activity 取得元のActivityを指定します。
     * @return 置換前文字列を返します。エラーの場合nullを返します。
     */
    public static String getOldString(Activity activity)
    {
        // Intentを取得 
        Intent intent = activity.getIntent();

        // nullの場合は終了
        if(intent == null)
        {
            return null;
        }

        // Actionを取得
        String action = intent.getAction();
        
        // Actionが一致しない場合は終了
        if(action == null || !action.equals(ACTION_INTERCEPT))
        {
            return null;
        }

        // 置換前文字列を取得
        return intent.getStringExtra(EXTRA_REPLACE_KEY);
    }

    /**
     * 置換後文字列を設定します。
     * 
     * @param activity 設定先のActivityを指定します。
     * @param text 設定する文字列
     */
    public static void setNewString(Activity activity, String text)
    {
        // Intentを生成
        Intent intent = new Intent();

        // 置換後文字列を設定
        intent.putExtra(EXTRA_REPLACE_KEY, text);

        // 結果として設定
        activity.setResult(Activity.RESULT_OK, intent);
    }
}

キャンディーのラッパークラス

  • Simejiで利用できるキャンディーのラッパークラス
import java.util.ArrayList;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Intent;

/*
<intent-filter>
<action android:name="com.adamrocker.android.simeji.ACTION_INJECTION"></action>
<category android:name="com.adamrocker.android.simeji.CANDIDATES"></category>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
*/

/**
 * キャンディーラッパークラス
 */
public class Candy
{
    // Action定数
    private static final String ACTION_INJECTION = "com.adamrocker.android.simeji.ACTION_INJECTION";
    
    // Extra定数
    private static final String EXTRA_CANDIDATE_KEY = "candidate_key";
    
    // コンストラクタ
    private Candy()
    {
    }
    
    /**
     * キャンディーに対応したIntentを持っているか調べます。
     * 
     * @param activity 対象のActivityを指定します。
     * @return キャンディー対応ならtrue、そうでない場合はfalseを返します。
     */
    public static boolean hasCandyIntent(Activity activity)
    {
        // Intentを取得
        Intent intent = activity.getIntent();
        
        // Intentがnullの場合
        if(intent == null)
        {
            return false;
        }
        
        // Actionを取得        
        String action = intent.getAction();
        
        // Actionがnullの場合
        if(action == null)
        {
            return false;
        }
        
        // Actionが一致しない場合
        if(!action.equals(ACTION_INJECTION))
        {
            return false;
        }
        
        return true;
    }
    
    /**
     * 候補文字列を設定します。
     * 
     * @param activity 設定先のActivityを指定します。
     * @param list 候補文字列のリストを指定します。
     */
    public static void setCandidateStrings(Activity activity, ArrayList<String> list)
    {
        // JSONArrayを生成
        JSONArray array = new JSONArray(list);
        
        // Intentを生成
        Intent intent = new Intent();
        
        // 候補文字列を設定
        intent.putExtra(EXTRA_CANDIDATE_KEY, array.toString());
        
        // 結果として設定
        activity.setResult(Activity.RESULT_OK, intent);
    }
    
    /**
     * 候補文字列を設定します。
     * 
     * @param activity 設定先のActivityを指定します。
     * @param array 候補文字列の配列を指定します。
     */
    public static void setCandidateStrings(Activity activity, String[] array)
    {
        // ArrayListを生成
        ArrayList<String> list = new ArrayList<String>();
        
        // ArrayListに文字列を詰める
        for(String text : array)
        {
            list.add(text);
        }
        
        // 別のバージョンを呼び出す
        setCandidateStrings(activity, list);
    }
}
最終更新:2014年07月02日 00:25