android 簡單對話框實現


1.實現效果:

原始界面:                                       點擊按鈕之后,顯示對話框                點擊對話框后的確定按鈕后,顯示一段文字

           

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context="com.example.dialoginterface.MainActivity">
<TextView
android:layout_marginTop="30dp"
android:layout_marginLeft="50dp"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:layout_marginLeft="50dp"
android:id="@+id/button"
android:text="@string/str_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:textSize="30sp"
android:layout_marginLeft="50dp"
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

java文件:
public class MainActivity extends Activity {
private Button bt;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.button);
tv=(TextView)findViewById(R.id.text);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//創建一個對話框對象
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
//對對話框內容進行定義
builder.setTitle(R.string.app_about);
builder.setMessage(R.string.app_about_msg);
//定義對話框內容的點擊事件,注意后面還有個show,否則不會顯示對話框
builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener(){
@Override
//定義點擊對話框按鈕后執行的動作,這里是添加一個textview的內容
public void onClick(DialogInterface dialog, int which) {
tv.setText("這是點擊對話框按鈕后,才會顯示的內容!");
}
}).show();
}
});
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM