Minggu, 22 September 2013

Create Dialog with List, using AlertDialog.Builder setItems()

You can add list to Dialog, use the setItems() method of AlertDialog.Builder. Because the list appears in the dialog's content area, the dialog cannot show both a message and list.


Dialog with ListView, using AlertDialog.Builder setItems()
Dialog with ListView, using AlertDialog.Builder setItems()

package com.example.androidlistdialog;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class MainActivity extends Activity {

Button buttonOpenDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOpenDialog = (Button)findViewById(R.id.opendialog);
buttonOpenDialog.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
openDialog();
}});
}

private void openDialog(){

final String[] days = {
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
};

AlertDialog.Builder myDialog =
new AlertDialog.Builder(MainActivity.this);
myDialog.setTitle("My Dialog with ListView");
  myDialog.setItems(days, new DialogInterface.OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
String item = days[which];
Toast.makeText(MainActivity.this,
item, Toast.LENGTH_LONG).show();

}});

myDialog.setNegativeButton("Cancel", null);

myDialog.show();
}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android-coding.blogspot.com" />
<Button
android:id="@+id/opendialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Dialog"/>

</LinearLayout>


Related: Create Dialog with traditional ListView, using AlertDialog.Builder.

0 komentar:

Posting Komentar

Copyright © 2012 Codding News All Right Reserved