Zi 字媒體
2017-07-25T20:27:27+00:00
一般來說我們使用到AlertDialog頂多是寫個文字或是改改標題
但如果想往AlertDialog裡面擺放其他的元件該怎麼辦呢?
比如說我想讓對話窗裡面顯示一個小星星之類的,如下圖
我們會使用到LayoutInflater,View來加載外部的布局(layout)
示範
XML
首先新增兩個XML檔案
activity_main.xml
xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btn_Click"
android:text="Dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
android.support.constraint.ConstraintLayout>
xll.xml
xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ig"
android:layout_width="131dp"
android:layout_height="148dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@android:drawable/btn_star_big_on" />
android.support.constraint.ConstraintLayout>
JAVA
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_Click(View v) {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View imageEnterView = layoutInflater.inflate(R.layout.xll, null);
ImageView xll_lv = (ImageView) imageEnterView.findViewById(R.id.ig);
new AlertDialog.Builder(this)
.setView(imageEnterView)
.setTitle("視窗")
.setPositiveButton("OK", null).show();
}
}
相關文章:
[Android] Android 程式設計教學
寫了
5860316篇文章,獲得
23313次喜歡