MainActivity如下:
main.xml如下:
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.Builder; import android.app.Dialog; import android.content.DialogInterface; public class MainActivity extends Activity { private Button mToastButton; private Button mAlertDialogButton; private Dialog mDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mToastButton=(Button) findViewById(R.id.toastButton); mToastButton.setOnClickListener(new ButtonOnClickListenerImpl()); mAlertDialogButton=(Button) findViewById(R.id.alertDialogButton); mAlertDialogButton.setOnClickListener(new ButtonOnClickListenerImpl()); } private class ButtonOnClickListenerImpl implements OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.toastButton: Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_info), Toast.LENGTH_LONG).show(); break; case R.id.alertDialogButton: Builder builder=new Builder(MainActivity.this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle(getResources().getString(R.string.dialog_title)); builder.setMessage(R.string.dialog_message); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { Toast.makeText(MainActivity.this, getResources().getString(R.string.dialog_no), Toast.LENGTH_SHORT).show(); } }); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { Toast.makeText(MainActivity.this, getResources().getString(R.string.dialog_ok), Toast.LENGTH_SHORT).show(); } }); mDialog=builder.create(); mDialog.show(); break; default: break; } } } }
main.xml如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" android:orientation="vertical" > <Button android:id="@+id/toastButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/toast_tip" android:layout_marginTop="100dip" android:textSize="20sp" /> <Button android:id="@+id/alertDialogButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_tip" android:layout_marginTop="100dip" android:textSize="20sp" /> </LinearLayout>