android 使用xml布局自己的对话框
android 使用xml布局自己的對(duì)話框
實(shí)現(xiàn)方法:通過setView(view) 來設(shè)置dialog顯示的布局:
運(yùn)行效果:
代碼如下:
主要Activity:
public class MainActivity extends Activity {
Button button;
View view;
LayoutInflater inflate;
AlertDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
inflate = LayoutInflater.from(this);
button.setOnClickListener(new OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
view = inflate.inflate(R.layout.dialog, null);
dialog = new AlertDialog.Builder(MainActivity.this).setView(view).show();
((Button)view.findViewById(R.id.dialog_button)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
view = null;
}
});
}
}
主要布局文件:
<RelativeLayout 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"
? ? tools:context=".MainActivity" >
? ? <Button android:id="@+id/button"
? ? ? ? android:layout_width="wrap_content"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:layout_centerHorizontal="true"
? ? ? ? android:layout_centerVertical="true"
? ? ? ? android:text="showDialog" />
</RelativeLayout>
dialog布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? xmlns:tools="http://schemas.android.com/tools"
? ? android:layout_width="wrap_content"
? ? android:layout_height="wrap_content" ? ?
? ? android:orientation="vertical"
? ? android:background="@drawable/dialog_bg"
? ? tools:context=".MainActivity" >
? ? <LinearLayout android:layout_width="fill_parent"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:gravity="center">
? ? ? ??
? ? <TextView android:layout_width="wrap_content"
? ? ? ? android:layout_height="wrap_content"
? ? ? ? android:text="這是一個(gè)對(duì)話框" ? ?
? ? ? ? android:textColor="#0f0" ? ?
? ? ? ? android:textSize="18sp"
? ? ? ? android:layout_margin="5dp"
? ? ? ? android:gravity="center"/>
? ? </LinearLayout>
? ??
? ? <View android:layout_width="fill_parent"
? ? ? ? android:layout_height="2dp"
? ? ? ? android:background="@drawable/dialog_line"/>
? ? <RelativeLayout android:layout_width="fill_parent"
? ? ? ? android:layout_height="fill_parent">
? ? ? ??
? ? ? ? <Button android:id="@+id/dialog_button"
? ? ? ? ? ? android:layout_width="wrap_content"
? ? ? ? ? ? android:layout_height="wrap_content"
? ? ? ? ? ? android:layout_centerInParent="true"
? ? ? ? ? ? android:text="確定"/>
? ? </RelativeLayout>
</LinearLayout>
用到的資源圖:
總結(jié)
以上是生活随笔為你收集整理的android 使用xml布局自己的对话框的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Photoshop自由变换图形大小
- 下一篇: android 继承dialog自定义