android动态换肤系列1——android命名空间的使用

本文介绍如何在Android开发中使用自定义属性扩展View功能,通过声明命名空间、设置属性值及在自定义View中读取这些值来实现。示例展示了从XML布局文件到Java代码的具体实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、声明:xmlns:thinking="http://schemas.android.com/thinking"

2、使用:thinking:test_str="yuyong"

3、获取:String str = attrs.getAttributeValue(
"http://schemas.android.com/thinking", "test_str");


示例:

activity_main.xml文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:thinking="http://schemas.android.com/thinking"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.thinking.skintest.MyText
        android:id="@+id/txt_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        thinking:test_str="yuyong" />
</RelativeLayout>

MyText.java文件

package com.thinking.skintest;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyText extends TextView {
// 这两个函数是自定义View必须实现的
public MyText(Context context) {
super(context);
}
public MyText(Context context, AttributeSet attrs) {
super(context, attrs);
String str = attrs.getAttributeValue(
"http://schemas.android.com/thinking", "test_str");

this.setText(str + "_" + this.getText());
}
}

MainActivity.java文件

package com.thinking.skintest;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值