android 自定义命名空间

简介: 引用:http://hi.baidu.com/%BD%F0%D3%F1kl_y/blog/item/3fad60c2e33d100d0ef47710.html   一、统一的用户界面是可以使得应用程序更友好。

引用:http://hi.baidu.com/%BD%F0%D3%F1kl_y/blog/item/3fad60c2e33d100d0ef47710.html

 

一、统一的用户界面是可以使得应用程序更友好。要做到用户界面的统一,我们就必须用到风格(style)和主题(theme)。
自定义一个View的方法步骤如下:
1、首先,在values文件夹下定义一个atts.xml的文件,描述自定义的控件的属性
在values/attrs.xml中:
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?>  
 <resources>  
    <declare-styleable name="TestView">  
        <attr name="textColor" format="color" />  
        <attr name="textSize" format="dimension" />  
        <attr name="imgBackground" format="integer" />  
        <attr name="textPaddingLeft" format="dimension"/>  
        <attr name="textPaddingTop" format="dimension"/>  
    </declare-styleable>  
 </resources>  
   <?xml version="1.0" encoding="utf-8"?>
    <resources>
       <declare-styleable name="TestView">
           <attr name="textColor" format="color" />
           <attr name="textSize" format="dimension" />
           <attr name="imgBackground" format="integer" />
           <attr name="textPaddingLeft" format="dimension"/>
           <attr name="textPaddingTop" format="dimension"/>
       </declare-styleable>
    </resources> 
2、其次,定义一个继承自View的类,如:TestView,使其实现View的方法
view plaincopy to clipboardprint?
package com.test.TestView;   
import android.content.Context;   
import android.content.res.TypedArray;   
import android.graphics.Canvas;   
import android.graphics.Color;   
import android.graphics.Paint;   
import android.util.AttributeSet;   
import android.view.View;   
  
public class TestView extends View {     
    private Paint mPaint;   
    private Context mContext;   
    private String mStr;   
    public TestView(Context context, AttributeSet attrs) {//构造方法;根据需要实现继承自View的方法   
        super(context, attrs);   
        mContext = context;   
        initMyView();   
        //对于我们自定义的类中,我们需要使用一个名为obtainStyledAttributes的方法来获取我们的定义。   
        TypedArray params = context.obtainStyledAttributes(attrs,R.styleable.MyView);   
        //得到自定义控件的属性值。   
        int backgroudId = params.getResourceId(R.styleable.MyView_imgBackground, 0);   
        if (backgroudId != 0)   
            setBackgroundResource(backgroudId);   
        int textColor = params.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);   
        setTextColor(textColor);   
        float textSize = params.getDimension(R.styleable.MyView_textSize, 36);   
        setTextSize(textSize);   
        float paddingLeft = params.getDimension( R.styleable.MyView_textPaddingLeft, 41);   
        float paddingTop = params.getDimension(R.styleable.MyView_textPaddingTop, 21);   
        setPaddings(paddingLeft, paddingTop);   
    }   
    @Override  
    protected void onDraw(Canvas canvas) {   
        super.onDraw(canvas);   
        if (mStr != null) {   
            canvas.drawText(mStr, 30, 60, mPaint);   
        }   
    }   
    private void initMyView() {   
        mPaint = new Paint();   
        mPaint.setColor(Color.WHITE);   
    }   
    private void setTextColor(int textColor) {   
        mPaint.setColor(0XFFAABBCC);   
    }   
    private void setTextSize(float textSize) {   
        mPaint.setTextSize(textSize);   
    }   
    void setText(String text) {   
        mStr = text;   
    }   
    private void setPaddings(float paddingLeft, float paddingTop) {   
        setPadding((int) paddingLeft, (int) paddingTop, 0, 0);   
    }   
}  
package com.test.TestView;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class TestView extends View {  
    private Paint mPaint;
    private Context mContext;
    private String mStr;
    public TestView(Context context, AttributeSet attrs) {//构造方法;根据需要实现继承自View的方法
        super(context, attrs);
        mContext = context;
        initMyView();
        //对于我们自定义的类中,我们需要使用一个名为obtainStyledAttributes的方法来获取我们的定义。
        TypedArray params = context.obtainStyledAttributes(attrs,R.styleable.MyView);
        //得到自定义控件的属性值。
        int backgroudId = params.getResourceId(R.styleable.MyView_imgBackground, 0);
        if (backgroudId != 0)
            setBackgroundResource(backgroudId);
        int textColor = params.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);
        setTextColor(textColor);
        float textSize = params.getDimension(R.styleable.MyView_textSize, 36);
        setTextSize(textSize);
        float paddingLeft = params.getDimension( R.styleable.MyView_textPaddingLeft, 41);
        float paddingTop = params.getDimension(R.styleable.MyView_textPaddingTop, 21);
        setPaddings(paddingLeft, paddingTop);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mStr != null) {
            canvas.drawText(mStr, 30, 60, mPaint);
        }
    }
    private void initMyView() {
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
    }
    private void setTextColor(int textColor) {
        mPaint.setColor(0XFFAABBCC);
    }
    private void setTextSize(float textSize) {
        mPaint.setTextSize(textSize);
    }
    void setText(String text) {
        mStr = text;
    }
    private void setPaddings(float paddingLeft, float paddingTop) {
        setPadding((int) paddingLeft, (int) paddingTop, 0, 0);
    }

3、然后,在Layout文件中应用该自定义的view,如下:
如在main.xml中
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
               xmlns:app="http://schemas.android.com/apk/res/com.test.TestView"     
               android:orientation="vertical" android:layout_width="fill_parent"  
               android:layout_height="fill_parent">  
    <com.test.TestView.TestView  
              android:id="@+id/myview"  
              android:layout_width="fill_parent"  
              android:layout_height="fill_parent"  
              app:textColor="#FFFFFFFF"  
              app:textSize="40dip"  
              app:textPaddingLeft="40dip"  
              app:textPaddingTop="40dip"  
              app:imgBackground="@drawable/bg" />  
 </LinearLayout>  
  <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 xmlns:app="http://schemas.android.com/apk/res/com.test.TestView"  
                 android:orientation="vertical" android:layout_width="fill_parent"
                 android:layout_height="fill_parent">
      <com.test.TestView.TestView
                android:id="@+id/myview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                app:textColor="#FFFFFFFF"
                app:textSize="40dip"
                app:textPaddingLeft="40dip"
                app:textPaddingTop="40dip"
                app:imgBackground="@drawable/bg" />
   </LinearLayout> 
说明:上述红色部分——xmlns:app="http://schemas.android.com/apk/res/com.test.TestView"是首先声明命名空间。命名空间为app.路径是http://schemas.android.com/apk/res/这一部分是不变的,后面接的是R的路径:com.test.TestView.R。然后在自定义控件的xml描述中就可以这样使用app:value="true"。这样就实现了自定义控件的初始化赋值。
4、然后就是使用了,在自己的Activity 中
view plaincopy to clipboardprint?
public class TestActivity extends Activity {   
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);   
          
        TestView mTextView=(TestView)findViewById(R.id.TestView);   
        mTextView.setText("自定义的View");   
    }   
}  
public class TestActivity extends Activity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        TestView mTextView=(TestView)findViewById(R.id.TestView);
        mTextView.setText("自定义的View");
    }

5、另外:

以下内容转自:http://www.android123.com.cn/androidkaifa/591.html

    对于Android系统的自定义View可能大家都熟悉了,对于自定义View的属性添加,以及Android的Layout的命名空间问题,很多网友还不是很清楚,今天Android123一起再带大家温习一下

view plaincopy to clipboardprint?
CwjView myView=new CwjView(context);  
CwjView myView=new CwjView(context);     

  如果用于游戏或整个窗体的界面,我们可能直接在onCreate中setContentView(myView); 当然如果是控件,我们可能会需要从Layout的xml中声明,比如

view plaincopy to clipboardprint?
<cn.com.android123.CwjView  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
/>  
      <cn.com.android123.CwjView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
      />

  当然,我们也可以直接从父类声明比如

view plaincopy to clipboardprint?
<View class="cn.com.android123.CwjView"  
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
/>  
       <View class="cn.com.android123.CwjView"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
       />

   上面我们仅用了父类View的两个属性,均来自android命名空间,而名称为layout_width或layout_height,我们自定义的控件可能有更多的功能,比如

view plaincopy to clipboardprint?
<cn.com.android123.CwjView    
      android:layout_width="wrap_content"  
      android:layout_height="wrap_content"  
     cwj:age="22"  
     cwj:university="sjtu"  
     cwj:city="shanghai"  
/>  
    <cn.com.android123.CwjView 
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
         cwj:age="22"
         cwj:university="sjtu"
         cwj:city="shanghai"
    />

 我们可以看到上面的三个属性,是我们自定义的。作为标准xml规范,可能还包含了类似 xmlns:android="http://schemas.android.com/apk/res/android"  这样的语句,对于定义完整的View,我们的命名空间为cwj,这里可以写为 

       xmlns:cwj=http://schemas.android.com/apk/res/cn.com.android123.cwjView 或       

       xmlns:cwj=http://schemas.android.com/apk/res/android 都可以。

  对于定义的cwj命名空间和age、university以及city的三个属性我们如何定义呢? 在工程的res/values目录中我们新建一个cwj_attr.xml文件,编码方式为utf-8是一个好习惯,内容如下

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8" ?>  
<resources>  
    <declare-styleable name="CwjView">  
       <attr name="age" format="integer" />  
       <attr name="city" format="string" />  
       <attr name="university" format="string" />  
   </declare-styleable>  
</resources>  
    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
        <declare-styleable name="CwjView">
           <attr name="age" format="integer" />
           <attr name="city" format="string" />
           <attr name="university" format="string" />
       </declare-styleable>
    </resources>

  这里我们可能对format不是很熟悉,目前Android系统内置的格式类型有integer比如ProgressBar的进度值,float比如RatingBar的值可能是3.5颗星,boolean比如ToggleButton的是否勾选,string比如TextView的text属性,当然除了我们常见的基础类型外,Android的属性还有特殊的比如color是用于颜色属性的,可以识别为#FF0000等类型,当然还有dimension的尺寸类型,比如23dip,15px,18sp的长度单位,还有一种特殊的为reference,一般用于引用@+id/cwj @drawable/xxx这样的类型。

  当然什么时候用reference呢? 我们就以定义一个颜色为例子:

  <attr name="red" format="color|reference" />  这里我们用了逻辑或的运算符,定义的红色是颜色类型的,同时可以被引用。当然,对于我们自定义的类中,我们需要使用一个名为obtainStyledAttributes的方法来获取我们的定义。在我们自定义View的构造方法(Context context, AttributeSet attrs)的重载类型中可以用

view plaincopy to clipboardprint?
public CwjView(Context context, AttributeSet attrs) {   
    super(context, attrs);   
    TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.cwj_attr);   
    mAge = a.getInteger(R.styleable.CwjView_age, 22);   
    mCity = a.getString(R.styleable.CwjView_city, "shanghai");   
    mUniversity= a.getString(R.styleable.CwjView_university, "sjtu");           
    a.recycle(); //Android123提示大家不要忘了回收资源   
  
}  
    public CwjView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.cwj_attr);
        mAge = a.getInteger(R.styleable.CwjView_age, 22);
        mCity = a.getString(R.styleable.CwjView_city, "shanghai");
        mUniversity= a.getString(R.styleable.CwjView_university, "sjtu");        
        a.recycle(); //Android123提示大家不要忘了回收资源

    }

这样类的全局成员变量 mAge、mCity就获取了我们需要的内容,当然根据layout中的数值我们自定义的CwjView需要动态的处理一些数据的情况,可以使用AttributeSet类的getAttributeResourceValue方法获取。

view plaincopy to clipboardprint?
public CwjView(Context context, AttributeSet attrs){   
    super(context, attrs);   
    resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "age", 100);     
    resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "city", "shanghai");   
    //resID就可以任意使用了   
    public CwjView(Context context, AttributeSet attrs){
        super(context, attrs);
        resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "age", 100);  
        resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "city", "shanghai");
        //resID就可以任意使用了
 }

以上两种方法中,参数的最后一个数值为默认的

相关文章
|
4月前
|
Android开发 UED 计算机视觉
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
本文介绍了一款受游戏“金铲铲之战”启发的Android自定义View——线条等待动画的实现过程。通过将布局分为10份,利用`onSizeChanged`测量最小长度,并借助画笔绘制动态线条,实现渐变伸缩效果。动画逻辑通过四个变量控制线条的增长与回退,最终形成流畅的等待动画。代码中详细展示了画笔初始化、线条绘制及动画更新的核心步骤,并提供完整源码供参考。此动画适用于加载场景,提升用户体验。
406 5
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
|
4月前
|
Android开发
Android自定义view之利用PathEffect实现动态效果
本文介绍如何在Android自定义View中利用`PathEffect`实现动态效果。通过改变偏移量,结合`PathEffect`的子类(如`CornerPathEffect`、`DashPathEffect`、`PathDashPathEffect`等)实现路径绘制的动态变化。文章详细解析了各子类的功能与参数,并通过案例代码展示了如何使用`ComposePathEffect`组合效果,以及通过修改偏移量实现动画。最终效果为一个菱形图案沿路径运动,源码附于文末供参考。
|
4月前
|
Android开发 开发者
Android自定义view之利用drawArc方法实现动态效果
本文介绍了如何通过Android自定义View实现动态效果,重点使用`drawArc`方法完成圆弧动画。首先通过`onSizeChanged`进行测量,初始化画笔属性,设置圆弧相关参数。核心思路是不断改变圆弧扫过角度`sweepAngle`,并调用`invalidate()`刷新View以实现动态旋转效果。最后附上完整代码与效果图,帮助开发者快速理解并实践这一动画实现方式。
129 0
|
4月前
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
|
4月前
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
208 65
Android自定义view之网易云推荐歌单界面
|
4月前
|
XML 前端开发 Android开发
一篇文章带你走近Android自定义view
这是一篇关于Android自定义View的全面教程,涵盖从基础到进阶的知识点。文章首先讲解了自定义View的必要性及简单实现(如通过三个构造函数解决焦点问题),接着深入探讨Canvas绘图、自定义属性设置、动画实现等内容。还提供了具体案例,如跑马灯、折线图、太极图等。此外,文章详细解析了View绘制流程(measure、layout、draw)和事件分发机制。最后延伸至SurfaceView、GLSurfaceView、SVG动画等高级主题,并附带GitHub案例供实践。适合希望深入理解Android自定义View的开发者学习参考。
508 84
|
4月前
|
Android开发 开发者
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
本文详细介绍了如何通过自定义 `attrs.xml` 文件实现 Android 自定义 View 的属性配置。以一个包含 TextView 和 ImageView 的 DemoView 为例,讲解了如何使用自定义属性动态改变文字内容和控制图片显示隐藏。同时,通过设置布尔值和点击事件,实现了图片状态的切换功能。代码中展示了如何在构造函数中解析自定义属性,并通过方法 `setSetting0n` 和 `setbackeguang` 实现功能逻辑的优化与封装。此示例帮助开发者更好地理解自定义 View 的开发流程与 attrs.xml 的实际应用。
Android自定义View之不得不知道的文件attrs.xml(自定义属性)
|
4月前
|
前端开发 Android开发 UED
讲讲Android为自定义view提供的SurfaceView
本文详细介绍了Android中自定义View时使用SurfaceView的必要性和实现方式。首先分析了在复杂绘制逻辑和高频界面更新场景下,传统View可能引发卡顿的问题,进而引出SurfaceView作为解决方案。文章通过Android官方Demo展示了SurfaceView的基本用法,包括实现`SurfaceHolder.Callback2`接口、与Activity生命周期绑定、子线程中使用`lockCanvas()`和`unlockCanvasAndPost()`方法完成绘图操作。
102 3
|
4月前
|
Android开发 开发者
Android自定义view之围棋动画(化繁为简)
本文介绍了Android自定义View的动画实现,通过两个案例拓展动态效果。第一个案例基于`drawArc`方法实现单次动画,借助布尔值控制动画流程。第二个案例以围棋动画为例,从简单的小球直线运动到双向变速运动,最终实现循环动画效果。代码结构清晰,逻辑简明,展示了如何化繁为简实现复杂动画,帮助读者拓展动态效果设计思路。文末提供完整源码,适合初学者和进阶开发者学习参考。
Android自定义view之围棋动画(化繁为简)
|
10月前
|
缓存 前端开发 Android开发
安卓开发中的自定义视图:从零到英雄
【10月更文挑战第42天】 在安卓的世界里,自定义视图是一块画布,让开发者能够绘制出独一无二的界面体验。本文将带你走进自定义视图的大门,通过深入浅出的方式,让你从零基础到能够独立设计并实现复杂的自定义组件。我们将探索自定义视图的核心概念、实现步骤,以及如何优化你的视图以提高性能和兼容性。准备好了吗?让我们开始这段创造性的旅程吧!
146 1