Skip to content

Instantly share code, notes, and snippets.

@sakurabird
Created June 3, 2012 08:11
Show Gist options
  • Save sakurabird/2862537 to your computer and use it in GitHub Desktop.
Save sakurabird/2862537 to your computer and use it in GitHub Desktop.
ダイアログの上にListViewを表示してクリックした場所をToastで表示する
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
package com.sakurafish.android.example.myexamplelistondialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
final int DIALOG = 1;
Context mContext;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = getApplicationContext();
showDialog(DIALOG);
}
@Override
protected Dialog onCreateDialog(int id) {
String[] str1 = {
"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"
};
ArrayAdapter<String> arrayAdapter1 = new
ArrayAdapter<String>(this, R.layout.dir_list, str1);
ListView listView1 = new ListView(this);
listView1.setAdapter(arrayAdapter1);
// ListViewが選択されたときの挙動
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast toast = Toast.makeText(mContext, "Selected position=" + position,
Toast.LENGTH_SHORT);
toast.show();
}
});
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(listView1);
dialog.setTitle("ListViewTest");
dialog.setMessage("ListViewTest");
dialog.setView(layout);
dialog.setPositiveButton("はい", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
whichButton) {
setResult(RESULT_OK);
}
});
dialog.setNegativeButton("いいえ", new
DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int
whichButton) {
setResult(RESULT_CANCELED);
}
});
return dialog.create();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment