android

sd7880005 13年前發布 | 2K 次閱讀 html5未來

一、統一的用戶界面是可以使得應用程序更友好。要做到用戶界面的統一,我們就必須用到風格(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就可以任意使用了
 }

 本文由用戶 sd7880005 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!