In this post, we will create a Alert Box with radio Buttons.
Lets create a button which will trigger the alert box.
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Click Me" />
After creating the button, make changes in the java file.
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
Button b;
final CharSequence[] items={"Red","Green","Blue"};
AlertDialog.Builder builder;
AlertDialog alert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
builder=new AlertDialog.Builder(this);
builder.setTitle("Pick a Color");
builder.setSingleChoiceItems(items,-1,new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Color : "+items[which],Toast.LENGTH_LONG).show();
}
});
alert=builder.create();
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
alert.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Output should look like





No comments:
Post a Comment