LoginSignup
3
3

More than 5 years have passed since last update.

Android学習ノート_140729(ボタン、エディットテキスト、チェックボックス、ウェブビュー)

Posted at

Eclipseのプロジェクト数が増えてきたからか、なんとなく動作がもっさりしてきた気がするので、ワークスペースの場所を変更するなどした。ひと通りやったら本を買ってひと通り機能など理解したほうが良さそう。っと思ってカートに入れた。

あと、たまにEclipseで、AndroidManifest.xml is missingってメッセージが出てデバッグできなくなることがある。この場合は、プロジェクトを選択してメニュー>プロジェクト>クリーンでエラーが消えるようだ。

ボタン

ButtonEx.java
package org.cenkhor.buttonex;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class ButtonEx extends Activity implements OnClickListener {
    private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
    private EditText editText;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // レイアウトの作成
        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255, 255, 255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
        // レイアウトにボタンを追加
        layout.addView(makeButton("ダイアログの表示", "0"));
        layout.addView(makeButton("Y/Nダイアログの表示", "1"));
        layout.addView(makeButton("テキストダイアログの表示", "2"));
        layout.addView(makeButton(res2bmp(this, R.drawable.button), "3"));
    }

    private Button makeButton(String text, String tag) {
        Button button = new Button(this);
        // ボタンに表示するテキストをセット
        button.setText(text);
        // ボタンを識別するためにタグをセット
        button.setTag(tag);
        // オンクリックイベントを追加
        button.setOnClickListener(this);
        // レイアウトを設定
        button.setLayoutParams(new LinearLayout.LayoutParams(WC, WC));
        // 設定したボタンをビューに返す
        return button;
    }
    //シグネチャを変えて、イメージボタンを作る
    private ImageButton makeButton(Bitmap bmp, String tag) {
        //押下された状態のボタンのイメージをフィルターをかけて生成
        Bitmap pressed = filteringBmp(bmp, Color.LTGRAY,
                PorterDuff.Mode.MULTIPLY);
        //テキスト表示の通常のボタンと精製は一緒。
        ImageButton button = new ImageButton(this);
        button.setTag(tag);
        button.setOnClickListener(this);
        //StateListDrawableクラスは押下時と押下されていない状態をリストとして持つクラス
        StateListDrawable drawables = new StateListDrawable();
        //押下状態の定数を保存
        int statePressed = android.R.attr.state_pressed;
        //押下状態を定義
        drawables.addState(new int[] { statePressed }, new BitmapDrawable(
                pressed));
        //それ以外の状態を定義
        drawables.addState(new int[] {}, new BitmapDrawable(bmp));
        button.setBackgroundDrawable(drawables);
        button.setLayoutParams(new LinearLayout.LayoutParams(bmp.getWidth(),
                bmp.getHeight()));
        return button;
    }

    private static Bitmap filteringBmp(Bitmap bmp, int color,
            PorterDuff.Mode mode) {
        int w = bmp.getWidth();
        int h = bmp.getHeight();
        Bitmap result = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        BitmapDrawable bd = new BitmapDrawable(bmp);
        bd.setBounds(0, 0, w, h);
        bd.setColorFilter(color, mode);
        Canvas canvas = new Canvas(result);
        bd.draw(canvas);
        return result;
    }

    private static Bitmap res2bmp(Context context, int resId) {
        return BitmapFactory.decodeResource(context.getResources(), resId);
    }

    @Override
    public void onClick(View view) {
        int tag = Integer.parseInt((String) view.getTag());
        if (tag == 0) {
            showDialog(this, "ダイアログタイトルです", "ボタンが押下されました。\n改行コードは\\nです");
        } else if (tag == 1) {
            showYesNoDialog(ButtonEx.this, "Question Title", "Do you like it?",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                showDialog(ButtonEx.this, "YES時のタイトル",
                                        "YESが押下されました");
                            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                                showDialog(ButtonEx.this, "NO時のタイトル",
                                        "NOが押下されました");
                            }

                        }
                    });
        } else if (tag == 2) {
            editText = new EditText(this);
            showTextDialog(this, "テキストダイアログ", editText,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showDialog(ButtonEx.this, " ", editText.getText()
                                    .toString());
                        }
                    });
        } else if (tag == 3) {
            showDialog(this, "イメージボタンのタイトル", "イメージボタンが押下されました");
        }
    }

    private void showTextDialog(Context context, String title,
            EditText editText, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setView(editText);
        ad.setPositiveButton("OK", listener);
        ad.show();

    }

    private void showYesNoDialog(Context context, String title, String text,
            DialogInterface.OnClickListener listener) {
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(text);
        // YES側のボタン設定
        ad.setPositiveButton("YESボタン", listener);
        // NO側のボタン設定
        ad.setNegativeButton("NOボタン", listener);
        ad.show();
    }

    private void showDialog(Context context, String title, String text) {
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK", null);
        ad.show();
    }
}

イメージボタンのフィルタかけてボタンの状態に割り当てる部分は、正直理解できてないけど、まぁおいおいやっていけばいいかなと思っている。AlertDialog.Builderの書き方は結構定形っぽいので覚えておく。

エディットテキスト

EditText.java
package org.cenkhor.edittextex;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class EditTextEx extends Activity implements View.OnClickListener {
    private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
    private final static int MP = LinearLayout.LayoutParams.MATCH_PARENT;
    private EditText editText;
    private Button button;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.WHITE);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        editText = new EditText(this);
        editText.setText("Sample Text", EditText.BufferType.NORMAL);
        editText.setLayoutParams(new LinearLayout.LayoutParams(MP, WC));
        layout.addView(editText);

        button = new Button(this);
        button.setText("入力完了");
        button.setOnClickListener(this);
        button.setLayoutParams(new LinearLayout.LayoutParams(WC, WC));
        layout.addView(button);
    }

    @Override
    public void onClick(View view) {
        showDialog(this, "結果表示", "入力された文字列は、\n「" + editText.getText().toString() + "」\nです。");
    }

    private static void showDialog(Context context, String title, String message) {
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(message);
        ad.setPositiveButton("OK", null);
        ad.show();

    }
}

前のボタンのほうが難しかった気がする。

チェックボックス

CheckBoxEx.java
package org.cenkhor.checkboxex;

import android.R.anim;
import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

public class CheckBoxEx extends Activity implements View.OnClickListener {
    private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
    private final static String BR = System.getProperty("line.separator");

    private CheckBox checkBox;
    private RadioGroup radioGroup;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private Spinner spinner;
    private Button button;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        LinearLayout layout = new LinearLayout(this);

        layout.setBackgroundColor(Color.WHITE);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        checkBox = new CheckBox(this);
        checkBox.setText("チェックボックスのテキスト");

        //id
        checkBox.setId(0);

        checkBox.setTextColor(Color.rgb(255, 0, 0));
        checkBox.setChecked(true);
        checkBox.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(checkBox);

        radioButton1 = new RadioButton(this);
        radioButton1.setText("ラジオボタンのテキスト");
        radioButton1.setTextColor(Color.rgb(0, 255, 0));
        radioButton1.setId(1);

        radioButton2 = new RadioButton(this);
        radioButton2.setText("ラジオボタンのテキスト");
        radioButton2.setTextColor(Color.rgb(0, 0, 255));
        radioButton2.setId(2);

        radioGroup = new RadioGroup(this);
        radioGroup.addView(radioButton1);
        radioGroup.addView(radioButton2);
        radioGroup.check(1);
        radioGroup.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
        layout.addView(radioGroup);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        String[] items = {"red", "green", "blue"};
        for(String item :items){
            adapter.add(item);
        }
        spinner = new Spinner(this);
        spinner.setAdapter(adapter);
        spinner.setSelection(0);
        spinner.setLayoutParams(new LinearLayout.LayoutParams(WC, WC));
        layout.addView(spinner);

        button = new Button(this);
        button.setText("結果表示");
        button.setOnClickListener(this);
        button.setLayoutParams(new LinearLayout.LayoutParams(WC, WC));
        layout.addView(button);

    }

    @Override
    public void onClick(View view) {
        showDialog(this,"結果表示",
                "チェックボックス > " + checkBox.isChecked() + BR +  
                "ラジオボタン > " + radioGroup.getCheckedRadioButtonId() + BR + 
                "スピナー > " + spinner.getSelectedItem());
    }

    private static void showDialog(Context context, String title, String text) {
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK", null);
        ad.show();

    }
}

スピナーってドロップダウンリストみたいなものなんだというのを初めて知った。ローディングの待機状態に表示する回転してるやつのことだと思ってた。違う。

ウェブビュー

WebViewEx.java
package org.cenkhor.webviewex;

import java.security.PublicKey;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewEx extends Activity {

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Webビューの生成
        WebView webView = new WebView(this);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setSaveFormData(false);
        settings.setSupportZoom(false);

        webView.setWebViewClient(new WebViewClient(){
            public boolean shoudlOverrideUrlLoading(WebView view, String url){
                return false;
            }

            public void onRecievedError(WebView view, int errorCode, String description, String url){
                showDialog(WebViewEx.this, "エラー", "通信エラーです。");
            }

        });

        setContentView(webView);
        webView.loadUrl("http://google.com");   
    }
    private static void showDialog(Context context, String title, String text){
        AlertDialog.Builder ad = new AlertDialog.Builder(context);
        ad.setTitle(title);
        ad.setMessage(text);
        ad.setPositiveButton("OK", null);
        ad.show();
    }
}

このコードを書いてもしばらく動かないし、困った、ネットも繋がってるしとやっていると、AndroidManifest.xmlを編集しなくてはいけないようだ。

通信機能を使用する場合は、ユーザーにセキュリティ的に通知しなくてはいけないようだ。プロジェクトファイルにあるxmlファイルを直接編集した。

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

上記コードを追加(XMLなので書く階層に注意)。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3