ラベル AlertDialog の投稿を表示しています。 すべての投稿を表示
ラベル AlertDialog の投稿を表示しています。 すべての投稿を表示

2019年5月30日木曜日

android開発 シンプルなダイアログ表示

2019 Jun. 30.
2019 Jun. 29.
2019 Jun. 22.
2019 May 31.
2019 May 30.

参照元
https://developer.android.com/guide/topics/ui/dialogs
https://akira-watson.com/android/alertdialog.html
http://furudate.hatenablog.com/entry/2014/01/09/162421

[MainActivity]
package YOUR.PACKAGE.alertdialogsample;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    Button button_dialog1, button_dialog2, button_dialog3;
    private TextView text_view;
    private FragmentManager flagmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text_view = findViewById(R.id.text_view);
        button_dialog1 = findViewById(R.id.button_dialog1);
        button_dialog2 = findViewById(R.id.button_dialog2);
        button_dialog3 = findViewById(R.id.button_dialog3);


        // button_dialog1ボタンタップでAlertを表示させる
        button_dialog1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flagmentManager = getSupportFragmentManager();

                // DialogFragment を継承したAlertDialogFragment1のインスタンス
                AlertDialogFragment1 dialogFragment = AlertDialogFragment1.newInstance(100);
                // DialogFragmentの表示
                dialogFragment.show(flagmentManager, "test alert dialog1");
            }
        });


        // button_dialog2ボタンタップでダイアログのメッセージを変えたAlertを表示させる
        //   newInstance()への引数を変更してメッセージを変える
        button_dialog2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flagmentManager = getSupportFragmentManager();

                // DialogFragmentを継承したAlertDialogFragment2のインスタンス
                AlertDialogFragment1 dialogFragment = AlertDialogFragment1.newInstance(200);
                // DialogFragmentの表示
                dialogFragment.show(flagmentManager, "test alert dialog2");
            }
        });


        // button_dialog3ボタンタップでItemを選択するAlertを表示させる
        button_dialog3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flagmentManager = getSupportFragmentManager();

                // DialogFragment を継承したAlertDialogFragmentのインスタンス
                AlertDialogFragment2 dialogFragment = new AlertDialogFragment2();
                // DialogFragmentの表示
                dialogFragment.show(flagmentManager, "test alert dialog");
            }
        });
    }


    public void setTextView(String message){
        text_view.setText(message);
    }


    /*
     * DialogFragmentを継承したクラスAlertDialogFragment1
     */
    public static class AlertDialogFragment1 extends DialogFragment {

        /*
         * コンストラクタを記述してはならない。
         * newInstance()でのsetArguments、onCreateDialog()でのgetArgumentsを利用する。
         */
        public static AlertDialogFragment1 newInstance( int requestCode) {
            AlertDialogFragment1 fragment = new AlertDialogFragment1();

            Bundle arguments = new Bundle();
            arguments.putInt("reqCode", requestCode);
            fragment.setArguments(arguments);

            return fragment;
        }

        @Override
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            int requestCode = getArguments().getInt("reqCode");

            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

            switch (requestCode) {
                case 100:
                    alert.setTitle("Test AlertDialog1");
                    alert.setMessage("Message is 100");
                    break;

                case 200:
                    alert.setTitle("Test AlertDialog2");
                    alert.setMessage("Message is 200");
                    break;

            }
            alert.setPositiveButton(R.string.dialog_ok, null);

            return alert.create();
        }
    }


    /*
     * DialogFragmentを継承したクラスAlertDialogFragment2
     */
    public static class AlertDialogFragment2 extends DialogFragment {
        // 選択肢のリスト
        private String[] menulist = {"選択(1)","選択(2)","選択(3)"};

        @Override
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

            alert.setTitle("Test AlertDialog3");
            alert.setItems(menulist, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int idx) {
                    // 選択1
                    if (idx == 0) {
                        setMassage(menulist[0]);
                    }
                    // 選択2
                    else if (idx == 1) {
                        setMassage(menulist[1]);
                    }
                    // 選択3, idx == 2
                    else{
                        setMassage(menulist[2]);
                    }
                }
            });
            return alert.create();
        }


        private void setMassage(String message) {
            MainActivity mainActivity = (MainActivity) getActivity();
            if (mainActivity != null) {
                mainActivity.setTextView(message);
            }
        }
    }
}

2018年1月21日日曜日

android AlertDialog内にinflateしたLayout内のViewへのアクセス

android AlertDialog内にinflateしたLayout内のViewへのアクセス

2018 Jan. 21.

Viewへのアスセスにはそれが所属するLayoutを指定する。


LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View myLayout = inflater.inflate(R.layout.my_layout, null);
TextView myTextView = (TextView)myLayout.findViewById(R.id.my_text_view);
myTextView.setText("Hello.");

2018年1月4日木曜日

androidプログラミング

androidプログラミング

2018 Jan. 06.
2018 Jan. 04.
2018 Jan. 03.
2017 Nov. 23.
2017 Aug. 16.

android, プログラミング, emulator, context, 1行, 読み込み,SD, ファイル読み込み, AlertDialog


preferenceで配列を扱う

https://qiita.com/ueno-yuhei/items/d51c00c5be3971f4cd40

コマンドラインからのemulator起動

$ Android/Sdk/tools/emulator -avd EMULATOR -qemu -m 512 -enable-kvm
EMULATOR: advの名前

context

参考サイト
http://yuki312.blogspot.jp/2012/02/thisgetapplicationcontextactivityapplic.html

1行読み込み


BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
    e.printStackTrace();
    if (br != null) try {
        br.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

String str;
try {
    while((str = br.readLine()) != null){
        Log.v("Read",str);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

SDカード上のファイルの読み込み


private String filename = "hoge.txt";
private File directory = Environment.getExternalStorageDirectory();
private String filepath = directory.getAbsolutePath() + "/YourDir/" + filename;

private File file = new File(filepath);

// SDカードマウント状態

final String state = Environment.getExternalStorageState();

if (!state.equals(Environment.MEDIA_MOUNTED)) {

    try {
      throw new IOException("No Mount");
  } catch (IOException e) {
      e.printStackTrace();
  }
}

BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
    e.printStackTrace();
    if (br != null) try {
        br.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

String str;
try {
    while((str = br.readLine()) != null){
        Log.v("Read",str);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (br != null) {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AlertDialog setItems()利用時のコードと挙動



サンプル1 ダイアログにボタンを置かず、アイテムをクリックすれば前画面に戻る

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn = (Button)findViewById(R.id.btn);
    btn.setText("Show Dialog");
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        final CharSequence[] items = {"car", "train", "byke"};
        new AlertDialog.Builder(MainActivity.this)
          .setTitle("Select tool")
          .setIcon(R.drawable.myIcon)
          .setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int which) {
              btn.setText(String.format("%sが選択されました。",items[which]));
            }
          })
          .show();
      }
    });
  }
}

サンプル2 ダイアログにボタンを置かず、アイテムをクリックしても前画面に戻らない

public class MainActivity extends Activity implements DialogInterface.OnClickListener {
    final String[] items = {"car", "train", "byke"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button btn = (Button)findViewById(R.id.btn);
        btn.setText("Show Dialog");
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                myShowDialog("Not Selected");
            }
        });
    }

    @Override
    public void onClick(DialogInterface dlg, int which) {
        myShowDialog(items[which]);
    }

    public void myShowDialog(final String titleStr) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(titleStr);
        dialog.setIcon(R.drawable.myIcon);
        dialog.setItems(items, this);
        dialog.show();
    }
}

サンプル3 ダイアログにボタンを置くが、アイテムのクリックでは前画面に戻らない

public class MainActivity extends Activity implements DialogInterface.OnClickListener {
    TextView tv;
    final String[] items = {"car", "train", "byke"};
    final List listItems = Arrays.asList(items); //配列をList型オブジェクトに変換

    @Override
    public void onClick(DialogInterface dlg, int which) {
        Log.v("dialog_which", String.valueOf(which)); // int of order of items
        showDialog(items[which]);
    }

    public void showDialog(final String titleStr) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(titleStr);
        dialog.setIcon(R.drawable.myIcon);
        dialog.setItems(items, this);

        dialog.setPositiveButton("決 定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int index) {
                Log.v("dialog_index", String.valueOf(index));  // unexpected int
                tv.setText(titleStr);
            }
        });

        dialog.setNeutralButton("前 へ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int index) {
                Log.v("dialog_index", String.valueOf(index)); // unexpected int
                int i = listItems.indexOf(titleStr); //list内に引数の要素が存在する最小のインデックスを返す
                int numArray = (i+3-1)%3;
                tv.setText(items[numArray]);
            }
        });

        dialog.setNegativeButton("2つ前へ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int index) {
                Log.v("dialog_index", String.valueOf(index));  // unexpected int
                int i = listItems.indexOf(titleStr); //list内に引数の要素が存在する最小のインデックスを返す
                int numArray = (i+3-2)%3;
                tv.setText(items[numArray]);
            }
        });
        dialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = ((TextView)findViewById(R.id.tv));
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                showDialog("");
            }
        });
    }
}