導航:首頁 > 操作系統 > android自定義switch樣式

android自定義switch樣式

發布時間:2022-08-17 02:46:59

『壹』 如何為android studio設置自定義的主題樣式

Android Studio默認主題IntelliJ,我們可以修改成黑色的Dracula的主題或者是Windows主題。 1、首先雙擊桌面AndroidStudio圖標,打開Android Studio。 2、選擇Android Studio菜單欄File——Settings選項 3、或者在工具欄中直接點擊Settings設置圖。詳細的可以看看安卓巴士教程:http://www.apkbus.com/thread-463460-1-1.html

『貳』 android 自定義view 怎麼規定view的樣式

android 自定義view的樣式的實現:

1.在values文件夾下,打開attrs.xml,其實這個文件名稱可以是任意的,寫在這里更規范一點,表示裡面放的全是view的屬性。

2.因為我們下面的實例會用到2個長度,一個顏色值的屬性,所以我們這里先創建3個屬性。

<declare-styleable name="rainbowbar">
<attr name="rainbowbar_hspace" format="dimension"></attr>
<attr name="rainbowbar_vspace" format="dimension"></attr>
<attr name="rainbowbar_color" format="color"></attr>
</declare-styleable>

舉例說明:

藍色的進度條

public class RainbowBar extends View {

//progress bar color
int barColor = Color.parseColor("#1E88E5");
//every bar segment width
int hSpace = Utils.dpToPx(80, getResources());
//every bar segment height
int vSpace = Utils.dpToPx(4, getResources());
//space among bars
int space = Utils.dpToPx(10, getResources());
float startX = 0;
float delta = 10f;
Paint mPaint;

public RainbowBar(Context context) {
super(context);
}

public RainbowBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public RainbowBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//read custom attrs
TypedArray t = context.obtainStyledAttributes(attrs,
R.styleable.rainbowbar, 0, 0);
hSpace = t.getDimensionPixelSize(R.styleable.rainbowbar_rainbowbar_hspace, hSpace);
vSpace = t.getDimensionPixelOffset(R.styleable.rainbowbar_rainbowbar_vspace, vSpace);
barColor = t.getColor(R.styleable.rainbowbar_rainbowbar_color, barColor);
t.recycle(); // we should always recycle after used
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(barColor);
mPaint.setStrokeWidth(vSpace);
}

.......
}

View有了三個構造方法需要我們重寫,這里介紹下三個方法會被調用的場景,

第一個方法,一般我們這樣使用時會被調用,View view = new View(context);

第二個方法,當我們在xml布局文件中使用View時,會在inflate布局時被調用,
<View layout_width="match_parent" layout_height="match_parent"/>。

第三個方法,跟第二種類似,但是增加style屬性設置,這時inflater布局時會調用第三個構造方法。
<View style="@styles/MyCustomStyle" layout_width="match_parent" layout_height="match_parent"/>。

『叄』 從源碼中淺析Android中怎麼利用attrs和styles定義控制項

1.attrs.xml:
我們知道Android的源碼中有attrs.xml這個文件,這個文件實際上定義了所有的控制項的屬性,就是我們在布局文件中設置的各類屬性
你可以找到attrs.xml這個文件,打開它,全選,右鍵->Show In->OutLine。可以看到整個文件的解構

我們大概可以看出裡面是Android中的各種屬性的聲明,比如textStyle這個屬性是這樣定義的:
java代碼
<!-- Default text typeface style. -->
<attr name="textStyle">
<flag name="normal" value="0" />
<flag name="bold" value="1" />
<flag name="italic" value="2" />
</attr>
那麼現在你知道,我們在寫android:textStyle的時候為什麼會出現normal,bold和italic這3個東西了吧,就是定義在這個地方。
再看看textColor:
Java代碼
<!-- Color of text (usually same as colorForeground). -->
<attr name="textColor" format="reference|color" />
format的意思是說:這個textColor可以以兩種方式設置,要麼是關聯一個值,要麼是直接設置一個顏色的RGB值,這個不難理解,因為我們可以平時也這樣做過。

也就是說我們平時在布局文件中所使用的各類控制項的屬性都定義在這裡面,那麼這個文件,除了定義這些屬性外還定義了各種具體的組件,比如TextView,Button,SeekBar等所具有的各種特有的屬性
比如SeekBar:

Java代碼
<declare-styleable name="SeekBar">
<!-- Draws the thumb on a seekbar. -->
<attr name="thumb" format="reference" />
<!-- An offset for the thumb that allows it to extend out of the range of the track. -->
<attr name="thumbOffset" format="dimension" />
</declare-styleable>
也許你會問SeekBar的background,等屬性怎麼沒有看到?這是因為Android中幾乎所有的組件都是從View中繼承下來的,SeekBar自然也不例外,而background這個屬性幾乎每個控制項都有,因此被定義到了View中,你可以在declare-styleable:View中找到它。

總結下,也就是說attrs.xml這個文件定義了布局文件中的各種屬性attr:***,以及每種控制項特有的屬性declare-styleable:***

2.styles.xml:
剛才的attrs.xml定義的是組件的屬性,現在要說的style則是針對這些屬性所設置的值,一些默認的值。

這個是SeekBar的樣式,我們可以看到,這裡面設置了一個SeekBar的默認的樣式,即為attrs.xml文件中的各種屬性設置初始值
Java代碼
<style name="Widget.SeekBar">
<item name="android:indeterminateOnly">false</item>
<item name="android:progressDrawable">@android:drawable/progress_horizontal</item>
<item name="android:indeterminateDrawable">@android:drawable/progress_horizontal</item>
<item name="android:minHeight">20dip</item>
<item name="android:maxHeight">20dip</item>
<item name="android:thumb">@android:drawable/seek_thumb</item>
<item name="android:thumbOffset">8dip</item>
<item name="android:focusable">true</item>
</style>
這個是Button的樣式:
Java代碼
<style name="Widget.Button">
<item name="android:background">@android:drawable/btn_default</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
<item name="android:textAppearance">?android:attr/textAppearanceSmallInverse</item>
<item name="android:textColor">@android:color/primary_text_light</item>
<item name="android:gravity">center_vertical|center_horizontal</item>
</style>

有了屬性和值,但是這些東西是如何關聯到一起的呢?它們如何被android的framework層所識別呢?

3.組件的源碼
我們看下TextView的源碼:
Java代碼
public TextView(Context context) {
this(context, null);
}//這個構造器用來給用戶調用,比如new TextView(this);

public TextView(Context context,
AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

public TextView(Context context,
AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);//為用戶自定義的TextView設置默認的style
mText = "";

//設置畫筆
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.density = getResources().getDisplayMetrics().density;
mTextPaint.setCompatibilityScaling(
getResources().getCompatibilityInfo().applicationScale);

mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHighlightPaint.setCompatibilityScaling(
getResources().getCompatibilityInfo().applicationScale);

mMovement = getDefaultMovementMethod();
mTransformation = null;

//attrs中包含了這個TextView控制項在布局文件中定義的屬性,比如android:background,android:layout_width等
//com.android.internal.R.styleable.TextView中包含了TextView中的針對attrs中的屬性的默認的值
//也就是說這個地方能夠將布局文件中設置的屬性獲取出來,保存到一個TypeArray中,為這個控制項初始化各個屬性
TypedArray a =
context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);

int textColorHighlight = 0;
ColorStateList textColor = null;
ColorStateList textColorHint = null;
ColorStateList textColorLink = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;

/*
* Look the appearance up without checking first if it exists because
* almost every TextView has one and it greatly simplifies the logic
* to be able to parse the appearance first and then let specific tags
* for this View override it.
*/
TypedArray appearance = null;
//TextView_textAppearance不太了解為什麼要這樣做?難道是為了設置TextView的一些默認的屬性?
int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1);
if (ap != -1) {
appearance = context.obtainStyledAttributes(ap,
com.android.internal.R.styleable.
TextAppearance);
}
if (appearance != null) {
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);

switch (attr) {
case com.android.internal.R.styleable.TextAppearance_textColorHighlight:
textColorHighlight = appearance.getColor(attr, textColorHighlight);
break;

case com.android.internal.R.styleable.TextAppearance_textColor:
textColor = appearance.getColorStateList(attr);
break;

case com.android.internal.R.styleable.TextAppearance_textColorHint:
textColorHint = appearance.getColorStateList(attr);
break;

case com.android.internal.R.styleable.TextAppearance_textColorLink:
textColorLink = appearance.getColorStateList(attr);
break;

case com.android.internal.R.styleable.TextAppearance_textSize:
textSize = appearance.getDimensionPixelSize(attr, textSize);
break;

case com.android.internal.R.styleable.TextAppearance_typeface:
typefaceIndex = appearance.getInt(attr, -1);
break;

case com.android.internal.R.styleable.TextAppearance_textStyle:
styleIndex = appearance.getInt(attr, -1);
break;
}
}

appearance.recycle();
}
//各類屬性
boolean editable = getDefaultEditable();
CharSequence inputMethod = null;
int numeric = 0;
CharSequence digits = null;
boolean phone = false;
boolean autotext = false;
int autocap = -1;
int buffertype = 0;
boolean selectallonfocus = false;
Drawable drawableLeft = null, drawableTop = null, drawableRight = null,
drawableBottom = null;
int drawablePadding = 0;
int ellipsize = -1;
boolean singleLine = false;
int maxlength = -1;
CharSequence text = "";
CharSequence hint = null;
int shadowcolor = 0;
float dx = 0, dy = 0, r = 0;
boolean password = false;
int inputType = EditorInfo.TYPE_NULL;

int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
//通過switch語句將用戶設置的,以及默認的屬性讀取出來並初始化
switch (attr) {
case com.android.internal.R.styleable.TextView_editable:
editable = a.getBoolean(attr, editable);
break;

case com.android.internal.R.styleable.TextView_inputMethod:
inputMethod = a.getText(attr);
break;

case com.android.internal.R.styleable.TextView_numeric:
numeric = a.getInt(attr, numeric);
break;

//更多的case語句...

case com.android.internal.R.styleable.TextView_textSize:
textSize = a.getDimensionPixelSize(attr, textSize);//設置當前用戶所設置的字體大小
break;

case com.android.internal.R.styleable.TextView_typeface:
typefaceIndex = a.getInt(attr, typefaceIndex);
break;
//更多的case語句...
}

通過上面的代碼大概可以知道,每個組件基本都有3個構造器,其中只傳遞一個Context上下文的那個構造器一般用來在java代碼中實例化使用。
比如你可以
Java代碼
TextView tv = new TextView(context);
來實例化一個組件。

最終調用的是第3個構造器
Java代碼
public TextView(Context context,
AttributeSet attrs,
int defStyle)

在這個構造器中為你設置了默認的屬性attrs和值styles。關鍵不在這里,而是後面通過使用下面的代碼
Java代碼
TypedArray a =
context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
來將屬性和值獲取出來,放到一個TypeArray中,然後再利用一個switch語句將裡面的值取出來。再利用這些值來初始化各個屬性。這個View最終利用這些屬性將這個控制項繪制出來。
如果你在布局文件中定義的一個View的話,那麼你定義的值,會被傳遞給構造器中的attrs和styles。也是利用同樣的方式來獲取出你定義的值,並根據你定義的值來繪制你想要的控制項。
再比如其實Button和EditText都是繼承自TextView。看上去兩個控制項似乎差異很大,其實不然。Button的源碼其實相比TextView變化的只是style而已:

『肆』 Android 怎樣在styles.xml中定義自己的樣式並引用樣式

下面是styles.xml文件中相關的部分:

[html] view plain print?

<stylename="text_font">

<itemname="android:textColor">#05b</item>

<itemname="android:textSize">18sp</item>

<itemname="android:textStyle">bold</item>

</style>

<stylename="content_font">

<itemname="android:textColor">#0f5</item>

<itemname="android:textSize">18sp</item>

<itemname="android:textStyle">normal</item>

</style>

<stylename="hint_text_font"parent="text_font">

<itemname="android:textColor">#f00</item>

</style>

<style name="text_font">
<item name="android:textColor">#05b</item>
<item name="android:textSize">18sp</item>
<item name="android:textStyle">bold</item>
</style>

<style name="content_font">
<item name="android:textColor">#0f5</item>
<item name="android:textSize">18sp</item>
<item name="android:textStyle">normal</item>
</style>

<style name="hint_text_font" parent="text_font">
<item name="android:textColor">#f00</item>
</style>


我們在界面元素中這樣引用:

[html] view plain print?

<TextViewstyle="@style/content_font"

android:id="@+id/textView1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello_world"/>

<Buttonstyle="@style/text_font"

android:id="@+id/button1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/test_IntentService"/>

<TextViewstyle="@style/hint_text_font"

android:id="@+id/hint"

android:text="@string/hint_text"

android:layout_height="wrap_content"

android:layout_width="fill_parent"/>

上面截圖就是通過自定義樣式實現的,例子來自android學習手冊,裡面有源碼。android學習手冊包含9個章節,108個例子,源碼文檔隨便看,例子都是可交互,可運行,源碼採用android studio目錄結構,高亮顯示代碼,文檔都採用文檔結構圖顯示,可以快速定位。360手機助手中下載,圖標上有貝殼:

『伍』 android 一個Activity中怎樣使用多個switch控制項

publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){
switch(view.getId()){
caseR.id.switch1:
if(isChecked){
statusText.setText("開");
}else{
statusText.setText("關");
}
break;
.....
}

不知道這是不是你要的效果

『陸』 如何自定義android Button樣式

在windows7操作系統Android studio中按照如下方法定義button的樣式。

1、首先使用Android studio創建一個項目,項目結構如下:

『柒』 android中switch控制項怎麼控制圖片的顯示隱藏

Android中自帶的Switch控制項在很多時候總覺得和整體系統風格不符,很多時候,自定義Switch是一種方法。
但其實不用這么麻煩,安卓自帶的Switch通過修改一些屬性,也可以達到和自定義Switch差不多的一個效果。
個人感覺,Switch的屬性設置和其他控制項還是有挺大區別的。
實現方式:
底部滑動條,在開關打開狀態為綠色,開關關閉狀態為灰色
在 res/drawable 文件夾下面,寫兩個滑動條的底圖 ,通過一個選擇器selector進行控制。

『捌』 android自定義控制項怎麼用

開發自定義控制項的步驟:
1、了解View的工作原理
2、 編寫繼承自View的子類
3、 為自定義View類增加屬性
4、 繪制控制項
5、 響應用戶消息
6 、自定義回調函數

一、View結構原理
Android系統的視圖結構的設計也採用了組合模式,即View作為所有圖形的基類,Viewgroup對View繼承擴展為視圖容器類。
View定義了繪圖的基本操作
基本操作由三個函數完成:measure()、layout()、draw(),其內部又分別包含了onMeasure()、onLayout()、onDraw()三個子方法。具體操作如下:
1、measure操作
measure操作主要用於計算視圖的大小,即視圖的寬度和長度。在view中定義為final類型,要求子類不能修改。measure()函數中又會調用下面的函數:
(1)onMeasure(),視圖大小的將在這里最終確定,也就是說measure只是對onMeasure的一個包裝,子類可以覆寫onMeasure()方法實現自己的計算視圖大小的方式,並通過setMeasuredDimension(width, height)保存計算結果。

2、layout操作
layout操作用於設置視圖在屏幕中顯示的位置。在view中定義為final類型,要求子類不能修改。layout()函數中有兩個基本操作:
(1)setFrame(l,t,r,b),l,t,r,b即子視圖在父視圖中的具體位置,該函數用於將這些參數保存起來;
(2)onLayout(),在View中這個函數什麼都不會做,提供該函數主要是為viewGroup類型布局子視圖用的;

3、draw操作
draw操作利用前兩部得到的參數,將視圖顯示在屏幕上,到這里也就完成了整個的視圖繪制工作。子類也不應該修改該方法,因為其內部定義了繪圖的基本操作:
(1)繪制背景;
(2)如果要視圖顯示漸變框,這里會做一些准備工作;
(3)繪制視圖本身,即調用onDraw()函數。在view中onDraw()是個空函數,也就是說具體的視圖都要覆寫該函數來實現自己的顯示(比如TextView在這里實現了繪制文字的過程)。而對於ViewGroup則不需要實現該函數,因為作為容器是「沒有內容「的,其包含了多個子view,而子View已經實現了自己的繪制方法,因此只需要告訴子view繪制自己就可以了,也就是下面的dispatchDraw()方法;
(4)繪制子視圖,即dispatchDraw()函數。在view中這是個空函數,具體的視圖不需要實現該方法,它是專門為容器類准備的,也就是容器類必須實現該方法;
(5)如果需要(應用程序調用了setVerticalFadingEdge或者setHorizontalFadingEdge),開始繪制漸變框;
(6)繪制滾動條;
從上面可以看出自定義View需要最少覆寫onMeasure()和onDraw()兩個方法。

二、View類的構造方法
創建自定義控制項的3種主要實現方式:
1)繼承已有的控制項來實現自定義控制項: 主要是當要實現的控制項和已有的控制項在很多方面比較類似, 通過對已有控制項的擴展來滿足要求。
2)通過繼承一個布局文件實現自定義控制項,一般來說做組合控制項時可以通過這個方式來實現。
注意此時不用onDraw方法,在構造廣告中通過inflater載入自定義控制項的布局文件,再addView(view),自定義控制項的圖形界面就載入進來了。
3)通過繼承view類來實現自定義控制項,使用GDI繪制出組件界面,一般無法通過上述兩種方式來實現時用該方式。

三、自定義View增加屬性的兩種方法:
1)在View類中定義。通過構造函數中引入的AttributeSet 去查找XML布局的屬性名稱,然後找到它對應引用的資源ID去找值。
案例:實現一個帶文字的圖片(圖片、文字是onDraw方法重繪實現)

public class MyView extends View {

private String mtext;
private int msrc;

public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
int resourceId = 0;
int textId = attrs.getAttributeResourceValue(null, "Text",0);
int srcId = attrs.getAttributeResourceValue(null, "Src", 0);
mtext = context.getResources().getText(textId).toString();
msrc = srcId;
}

@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.RED);
InputStream is = getResources().openRawResource(msrc);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
int bh = mBitmap.getHeight();
int bw = mBitmap.getWidth();
canvas.drawBitmap(mBitmap, 0,0, paint);
//canvas.drawCircle(40, 90, 15, paint);
canvas.drawText(mtext, bw/2, 30, paint);
}
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<com.example.myimageview2.MyView
android:id="@+id/myView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Text="@string/hello_world"
Src="@drawable/xh"/>

</LinearLayout>

屬性Text, Src在自定義View類的構造方法中讀取。

2)通過XML為View注冊屬性。與Android提供的標准屬性寫法一樣。
案例: 實現一個帶文字說明的ImageView (ImageView+TextView組合,文字說明,可在布局文件中設置位置)

public class MyImageView extends LinearLayout {

public MyImageView(Context context) {
super(context);
}

public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
int resourceId = -1;
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.MyImageView);
ImageView iv = new ImageView(context);
TextView tv = new TextView(context);
int N = typedArray.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = typedArray.getIndex(i);
switch (attr) {
case R.styleable.MyImageView_Oriental:
resourceId = typedArray.getInt(
R.styleable.MyImageView_Oriental, 0);
this.setOrientation(resourceId == 1 ? LinearLayout.HORIZONTAL
: LinearLayout.VERTICAL);
break;
case R.styleable.MyImageView_Text:
resourceId = typedArray.getResourceId(
R.styleable.MyImageView_Text, 0);
tv.setText(resourceId > 0 ? typedArray.getResources().getText(
resourceId) : typedArray
.getString(R.styleable.MyImageView_Text));
break;
case R.styleable.MyImageView_Src:
resourceId = typedArray.getResourceId(
R.styleable.MyImageView_Src, 0);
iv.setImageResource(resourceId > 0 ?resourceId:R.drawable.ic_launcher);
break;
}
}
addView(iv);
addView(tv);
typedArray.recycle();
}
}

attrs.xml進行屬性聲明, 文件放在values目錄下

<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="MyImageView">
<attr name="Text" format="reference|string"></attr>
<attr name="Oriental" >
<enum name="Horizontal" value="1"></enum>
<enum name="Vertical" value="0"></enum>
</attr>
<attr name="Src" format="reference|integer"></attr>
</declare-styleable>

</resources>

MainActivity的布局文件:先定義命名空間 xmlns:uview="http://schemas.android.com/apk/res/com.example.myimageview2" (com.example.myimageview2為你
在manifest中定義的包名)
然後可以像使用系統的屬性一樣使用:uview:Oriental="Vertical"

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:uview="http://schemas.android.com/apk/res/com.example.myimageview2"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<com.example.myimageview2.MyImageView
android:id="@+id/myImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
uview:Text="這是一個圖片說明"
uview:Src="@drawable/tw"
uview:Oriental="Vertical">
</com.example.myimageview2.MyImageView>

</LinearLayout>

四、控制項繪制 onDraw()

五、
六:自定義View的方法
onFinishInflate() 回調方法,當應用從XML載入該組件並用它構建界面之後調用的方法
onMeasure() 檢測View組件及其子組件的大小
onLayout() 當該組件需要分配其子組件的位置、大小時
onSizeChange() 當該組件的大小被改變時
onDraw() 當組件將要繪制它的內容時
onKeyDown 當按下某個鍵盤時
onKeyUp 當松開某個鍵盤時
onTrackballEvent 當發生軌跡球事件時
onTouchEvent 當發生觸屏事件時
onWindowFocusChanged(boolean) 當該組件得到、失去焦點時
onAtrrachedToWindow() 當把該組件放入到某個窗口時
onDetachedFromWindow() 當把該組件從某個窗口上分離時觸發的方法
onWindowVisibilityChanged(int): 當包含該組件的窗口的可見性發生改變時觸發的方法

『玖』 android中的switch開關和ios中的不同,這樣就需要通過動畫來實現一個iphone開關了

做IOS開發的都知道,IOS提供了一個具有動態開關效果的UISwitch組件,這個組件很好用效果相對來說也很絢麗,當我們去點擊開關的時候有動畫效果,但遺憾的是Android上並沒有給我們提供類似的組件(聽說在Android4.0的版本上提供了具有動態效果的開關組件,不過我還沒有去看文檔),如果我們想實現類似的效果那該怎麼辦了呢?看來又得去自定義了。
公司的產品最近一直在做升級,主要做的就是把界面做的更絢麗更美觀給用戶更好的體驗(唉,顧客是上帝......),其中的設置功能中就有開關按鈕,原來的開關做的是兩幅圖片,通過點擊圖片來給開關設置不同的狀態圖片,但是這種效果很死板和程序的整體風格不太協調,於是就想著實現類似於IOS中的開關效果。
拿著筆在圖紙上畫了畫,我實現的原理也是採用了兩幅圖片,一個整體的背景圖:和一個小滑塊圖:,用小滑塊圖實現在背景圖上滑動,當小滑塊滑到左邊時恰好遮擋了開字,就是顯示的關了,同樣原理當小滑塊滑動到右側時恰好遮擋了關字也就是現實開了,滑動的實現主要用的就是TranslateAnimation類,如有對TranslateAnimation不太熟悉的,問問度娘,她那有關TranslateAnimation的解說多了去了,畢竟自己動手,豐衣食足嘛,(*^__^*) 嘻嘻……
好了,老規矩來看一下項目結構吧:

工程中switch_button.xml文件就是對應的SwitchButton的布局文件,內容不需要解釋,你一看就懂

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/switch_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/switch_bg">

<ImageView
android:id="@+id/switch_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/switch_btn" />

</LinearLayout>

SwitchButton的布局文件中根節點是個LinearLayout,把它的背景設置成了一個含有開關文字的圖片,里邊包含一個ImageView,這個ImageView就是用來在LinearLayout中進行滑動的。
其中自定義開關組件就是都在wedgit包下的SwitchButton,那麼趕緊來看一下SwitchButton的代碼吧

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

public class SwitchButton extends LinearLayout {

/**
* 開關圖片
*/
private LinearLayout switchParent;
/**
* 滑塊圖片
*/
private ImageView switchButton;
/**
* 按鈕狀態,默認關閉
*/
private boolean isOn = false;
/**
* 滑塊需要滑動的距離
*/
private int scrollDistance;
/**
* 開關按鈕監聽器
*/
private SwitchChangedListner listner;

public SwitchButton(Context context) {
super(context);
initWedgits(context);
}

public SwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
initWedgits(context);
}

/**
* 初始化組件
*
* @param context
* 上下文環境
*/
private void initWedgits(Context context) {
try {
View view = LayoutInflater.from(context).inflate(
R.layout.switch_button, this);
switchParent = (LinearLayout) view.findViewById(R.id.switch_parent);
switchButton = (ImageView) view.findViewById(R.id.switch_button);
addListeners();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 添加事件監聽器
*/
private void addListeners() {
try {
switchParent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isOn = !isOn;
scrollSwitch();
if (null != listner) {
// 開關開發或者關閉的回調方法
listner.switchChanged(getId(), isOn);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 滑動開關
*/
private void scrollSwitch() {
// 獲取滑塊需要滑動的距離,滑動距離等於父組建的寬度減去滑塊的寬度
scrollDistance = switchParent.getWidth() - switchButton.getWidth();
// 初始化滑動事件
Animation animation = null;
if (isOn) {
animation = new TranslateAnimation(0, scrollDistance, 0, 0);
} else {
animation = new TranslateAnimation(scrollDistance, 0, 0, 0);
}
// 設置滑動時間
animation.setDuration(200);
// 滑動之後保持狀態
animation.setFillAfter(true);
// 開始滑動
switchButton.startAnimation(animation);
}

/**
* 獲取開關狀態
*
* @return 【true:打開】【false:關閉】
*/
public boolean isOn() {
return isOn;
}

/**
* 設置開關狀態
*
* @param isOn
* 開關狀態【true:打開】【false:關閉】
*/
public void setOn(boolean isOn) {
if (this.isOn == isOn) {
return;
}
this.isOn = isOn;
post(new Runnable() {
@Override
public void run() {
scrollSwitch();
}
});
}

/**
* 設置開關狀態監聽器
*
* @param listner
* 開關狀態監聽器
*/
public void setOnSwitchListner(SwitchChangedListner listner) {
this.listner = listner;
}

/**
* 開關狀態監聽器
*
* @author llew
*
*/
public interface SwitchChangedListner {
/**
* 開關狀態改變
*
* @param viewId
* 當前開關ID
* @param isOn
* 開關是否打開【true:打開】【false:關閉】
*/
public void switchChanged(Integer viewId, boolean isOn);
}
}

『拾』 Android開發如何設置Dialog樣式

黑色的這個dialog是系統默認的樣式,白色的是android4.0以上自帶的一個樣式,需要在manifest的application中引用@android:style/Theme.Holo.Light這個樣式

閱讀全文

與android自定義switch樣式相關的資料

熱點內容
程序員說不能說的秘密 瀏覽:700
在線shell編譯器 瀏覽:102
為什麼王者榮耀安卓轉蘋果成功登不上去 瀏覽:710
文件加密演算法可行性報告 瀏覽:60
a3雙面列印pdf 瀏覽:270
被命令文言文 瀏覽:717
c語言編譯器在線菜鳥 瀏覽:214
安卓如何使用華為手機助手 瀏覽:701
怎麼查看域伺服器名稱 瀏覽:775
如何把蘋果的視頻傳到安卓手機 瀏覽:612
介面伺服器怎麼使用 瀏覽:62
蘋果怎麼實現安卓全面屏手勢 瀏覽:977
拳皇97最強宏命令 瀏覽:921
linux安裝svn查看 瀏覽:850
內置函數計算絕對值python 瀏覽:88
千聊免費課程可以重新加密嗎 瀏覽:507
python能代替php嗎 瀏覽:253
phpexcel樣式 瀏覽:265
安卓手機有沒有什麼軟體可以阻止彈廣告的 瀏覽:306
linux區域網搭建伺服器 瀏覽:690