在xml中设置视图的自定义属性。

在xml中写出自定义的属性值方法。

实例:在xml中给自定义布局写出自定义属性的值。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <com.zq.androidservice.dialog.SelfView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:text="aaaa"
        app:background_color="@color/blue"
       />

  xmlns:app="http://schemas.android.com/apk/res-auto" 这一句话是用来命名空间的。前面的app可以随便改成任何你想要的自定义的名字。



1.首先需要你在values的styles中写你想要的属性与属性命名,与你给这些属性集合的命名。(这里是SelfView)

<resources>
 
   <declare-styleable name="SelfView">

        <attr name="background_color" format="color"/>
        <attr name="text" format="string"/>

    </declare-styleable>

</resources>

然后需要你在自定义视图的.java文件中获取绑定,调用AttributeSet的属性获取对应的你在value
private void init(Context context,AttributeSet attrs){
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.SelfView);
        int mColor = ta.getColor(R.styleable.SelfView_background_color, Color.BLACK);
        String mTextStr = ta.getString(R.styleable.SelfView_text );
        ta.recycle();  //注意回收
        Log.e("SelfView_text","SelfView_text = " + mTextStr);
    }

注意:此方法是需要你自定去手写,在自定义视图的构造器中去调用。获取到你在xml中设置的属性值,然后根据你的需求,做出相对应的处理。

绑定属性时,先是通过属性集的名字,获取属性集。然后是以属性集的名字做前缀,带下划线的形式,接上属性名,获取对应属性值。

之后获取到的属性值拿去做你想做的处理。


至此完毕~

要创建一个自定义 XML 弹窗,可以按照以下步骤进行: 1. 创建一个 XML 布局文件,定义你想要的弹窗视图。例如,你可以创建一个包含文本框、按钮等控件的布局文件。假设你的文件名为 `custom_dialog.xml`。 2. 在你的 Activity ,创建一个 AlertDialog.Builder 对象,并调用其 `setView()` 方法来设置弹窗的视图。例如: ```java AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.custom_dialog, null); builder.setView(view); ``` 这里的 `getLayoutInflater().inflate(R.layout.custom_dialog, null)` 方法用于将 `custom_dialog.xml` 文件转化为一个 View 对象。 3. 可以通过调用 AlertDialog.Builder 的其他方法来设置弹窗的属性,例如标题、按钮等。例如: ```java builder.setTitle("自定义弹窗"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 处理确定按钮的点击事件 } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 处理取消按钮的点击事件 } }); ``` 4. 调用 AlertDialog.Builder 的 `create()` 方法来创建 AlertDialog 对象,并显示出来。例如: ```java AlertDialog dialog = builder.create(); dialog.show(); ``` 这样就可以在你的 Android 应用创建一个自定义 XML 弹窗了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值