Sabtu, 21 September 2013

Create Dialog with ListView, using AlertDialog.Builder.

Dialog with ListView
Dialog with ListView

package com.example.androidlistdialog;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;

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(){

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

AlertDialog.Builder myDialog =
new AlertDialog.Builder(MainActivity.this);
myDialog.setTitle("My Dialog with ListView");

ListView listView = new ListView(MainActivity.this);
listView.setBackgroundColor(Color.argb(255, 255, 255, 255));
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, days);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
String item = (String)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this,
item, Toast.LENGTH_LONG).show();
}});

myDialog.setNegativeButton("Cancel", null);

myDialog.setView(listView);
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 List, using AlertDialog.Builder setItems()

0 komentar:

Posting Komentar

Copyright © 2012 Codding News All Right Reserved