當前位置:首頁 » 安卓系統 » android自定義switch

android自定義switch

發布時間: 2022-10-24 08:21:59

① android 自定義對話框怎麼關閉

1、在Dialog裡面有個dimiss()方法直接用你自定義的對話框的對象調用就好了!
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvCancle:
dismiss();
break;
}
}
2、用反射把view取出來,然後用view的findViewbyid找到button,注冊事件就好了

② android自定義對話框 怎麼設置關閉

在Dialog裡面有個dimiss()方法直接用你自定義的對話框的對象調用就好了!

java">@Override
publicvoidonClick(Viewv){
switch(v.getId()){
caseR.id.tvCancle:
dismiss();
break;
}
}

③ android 自定義switch樣式

修改後的MySwitch控制項介面基本與原Switch控制項一致,並且除了可支持所有SDK外,增加了2項小功能:
1. 支持用Track背景圖片的方式代替Texton Textoff等文字方式表現開關狀態
2.支持調整控制Switch的高度
下面貼出Switch修改的關鍵代碼:

/**
* <p>
* modified from android SDK 14(4.0) android.widget.Switch.
* <br/>
* <strong>new feature: </strong>
* <ol>
* <li>support SDK 1 or higher. </li>
* <li>you can use track drawable instead of text to display the changes of off-on state!</li>
* <li>you can control the Switch minimum height. </li>
* </ol>
* </p>
*
* @see {@link Switch}
* @author Wison
*/
public class MySwitch extends CompoundButton {
// Support track drawable instead of text
private Drawable mTrackOnDrawable;
private Drawable mTrackOffDrawable;

// Support minimum height
private int mSwitchMinHeight;

/**
* Construct a new Switch with a default style determined by the given theme attribute,
* overriding specific style attributes as requested.
*
* @param context The Context that will determine this widget's theming.
* @param attrs Specification of attributes that should deviate from the default styling.
* @param defStyle An attribute ID within the active theme containing a reference to the
* default style for this widget. e.g. android.R.attr.switchStyle.
*/
public MySwitch(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
Resources res = getResources();
mTextPaint.density = res.getDisplayMetrics().density;
//float scaledDensity = res.getDisplayMetrics().scaledDensity;
//mTextPaint.setCompatibilityScaling(res.getCompatibilityInfo().applicationScale);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Switch, defStyle, 0);

// off-on 模式: 圖片模式或文字模式,圖片模式是用Track背景圖片表示off-on的狀態,文字模式是用文字來表示off-on狀態。
mTrackOnDrawable = a.getDrawable(R.styleable.Switch_trackOn);
mTrackOffDrawable = a.getDrawable(R.styleable.Switch_trackOff);
if (checkTrackOffOnDrawable()) {
// 如果設定圖片模式,則默認顯示off狀態
mTrackDrawable = mTrackOffDrawable;
} else {
mTrackDrawable = a.getDrawable(R.styleable.Switch_track);
}

mThumbDrawable = a.getDrawable(R.styleable.Switch_thumb);
mTextOn = a.getText(R.styleable.Switch_textOn);
mTextOff = a.getText(R.styleable.Switch_textOff);
mThumbTextPadding = a.getDimensionPixelSize(R.styleable.Switch_thumbTextPadding, 0);
mSwitchMinWidth = a.getDimensionPixelSize(R.styleable.Switch_switchMinWidth, 0);

mSwitchMinHeight = a.getDimensionPixelSize(R.styleable.Switch_switchMinHeight, 0);

mSwitchPadding = a.getDimensionPixelSize(R.styleable.Switch_switchPadding, 0);

int appearance = a.getResourceId(R.styleable.Switch_switchTextAppearance, 0);
if (appearance != 0) {
setSwitchTextAppearance(context, appearance);
}
a.recycle();

ViewConfiguration config = ViewConfiguration.get(context);
mTouchSlop = config.getScaledTouchSlop();
mMinFlingVelocity = config.getScaledMinimumFlingVelocity();

// Refresh display with current params
refreshDrawableState();
setChecked(isChecked());
}

private boolean checkTrackOffOnDrawable() {
return mTrackOnDrawable != null && mTrackOffDrawable != null;
}

@SuppressLint("NewApi")
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOnLayout == null) {
mOnLayout = makeLayout(mTextOn);
}
if (mOffLayout == null) {
mOffLayout = makeLayout(mTextOff);
}
mTrackDrawable.getPadding(mTempRect);
final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth());
final int switchWidth = Math.max(mSwitchMinWidth,
maxTextWidth * 2 + mThumbTextPadding * 4 + mTempRect.left + mTempRect.right);

// final int switchHeight = mTrackDrawable.getIntrinsicHeight();
int switchHeight;
if (mSwitchMinHeight <= 0) {
switchHeight = mTrackDrawable.getIntrinsicHeight();
} else {
switchHeight = Math.max(mSwitchMinHeight, mTempRect.top + mTempRect.bottom);
}
mThumbWidth = maxTextWidth + mThumbTextPadding * 2;

mSwitchWidth = switchWidth;
mSwitchHeight = switchHeight;

super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int measuredHeight = getMeasuredHeight();
if (measuredHeight < switchHeight) {
if (Build.VERSION.SDK_INT >= 11) {
setMeasuredDimension(getMeasuredWidthAndState(), switchHeight);
} else {
setMeasuredDimension(getMeasuredWidth(), switchHeight);
}
}
}
@Override
public void setChecked(boolean checked) {
if (checkTrackOffOnDrawable()) {
mTrackDrawable = checked ? mTrackOnDrawable : mTrackOffDrawable;
refreshDrawableState();
}
super.setChecked(checked);
mThumbPosition = checked ? getThumbScrollRange() : 0;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the switch
int switchLeft = mSwitchLeft;
int switchTop = mSwitchTop;
int switchRight = mSwitchRight;
int switchBottom = mSwitchBottom;

if (checkTrackOffOnDrawable()) {
mTrackDrawable = getTargetCheckedState() ? mTrackOnDrawable : mTrackOffDrawable;
refreshDrawableState();
}

mTrackDrawable.setBounds(switchLeft, switchTop, switchRight, switchBottom);
mTrackDrawable.draw(canvas);
canvas.save()
mTrackDrawable.getPadding(mTempRect);
int switchInnerLeft = switchLeft + mTempRect.left;
int switchInnerTop = switchTop + mTempRect.top;
int switchInnerRight = switchRight - mTempRect.right;
int switchInnerBottom = switchBottom - mTempRect.bottom;
canvas.clipRect(switchInnerLeft, switchTop, switchInnerRight, switchBottom);

mThumbDrawable.getPadding(mTempRect);
final int thumbPos = (int) (mThumbPosition + 0.5f);
int thumbLeft = switchInnerLeft - mTempRect.left + thumbPos;
int thumbRight = switchInnerLeft + thumbPos + mThumbWidth + mTempRect.right;

mThumbDrawable.setBounds(thumbLeft, switchTop, thumbRight, switchBottom);
mThumbDrawable.draw(canvas);

// mTextColors should not be null, but just in case
if (mTextColors != null) {
mTextPaint.setColor(mTextColors.getColorForState(getDrawableState(),
mTextColors.getDefaultColor()));
}
mTextPaint.drawableState = getDrawableState();

Layout switchText = getTargetCheckedState() ? mOnLayout : mOffLayout;

if (switchText != null) {
canvas.translate((thumbLeft + thumbRight) / 2 - switchText.getWidth() / 2,
(switchInnerTop + switchInnerBottom) / 2 - switchText.getHeight() / 2);
switchText.draw(canvas);
}
canvas.restore();
}
}

下面是關鍵屬性聲明:
<declare-styleable name="Switch">

<!-- Drawable to use when the switch is in the checked/"on" state. -->
<attr name="trackOn" format="reference" />
<!-- Drawable to use when the switch is in the unchecked/"off" state. -->
<attr name="trackOff" format="reference" />
<!-- Minimum height for the switch component -->
<attr name="switchMinHeight" format="dimension" />

<!-- Drawable to use as the "thumb" that switches back and forth. -->
<attr name="thumb" format="reference" />
<!-- Drawable to use as the "track" that the switch thumb slides within. -->
<attr name="track" format="reference" />
<!-- Text to use when the switch is in the checked/"on" state. -->
<attr name="textOn" format="string" />
<!-- Text to use when the switch is in the unchecked/"off" state. -->
<attr name="textOff" format="string" />
<!-- Amount of padding on either side of text within the switch thumb. -->
<attr name="thumbTextPadding" format="dimension" />
<!-- TextAppearance style for text displayed on the switch thumb. -->
<attr name="switchTextAppearance" format="reference" />
<!-- Minimum width for the switch component -->
<attr name="switchMinWidth" format="dimension" />
<!-- Minimum space between the switch and caption text -->
<attr name="switchPadding" format="dimension" />
</declare-styleable>

④ android中switch控制項怎麼控制圖片的顯示隱藏

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

⑤ android如何自定義進行線程

Runnable begin = new Runnable(){
@Override
public void run(){
try{
Thread.sleep(2000);
Message msg = new Message();
msg.what = 100;
this.mHandler.sendMessage(msg);

}
catch(InterruptedException e){}
}
};

private Handler mHandler = new Handler() {

public void handleMessage(Message msg) {
switch (msg.what) {
case 100:
tv1.setBackgroundColor(Color.RED);

break;

}
};

⑥ 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中的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自定義控制項怎麼用

一、控制項自定義屬性介紹
以下示例中代碼均在values/attrs.xml 中定義,屬性均可隨意命名。
1. reference:參考某一資源ID。
示例:
<declare-styleable name = "名稱">

<attr name = "background" format = "reference" />
<attr name = "src" format = "reference" />
</declare-styleable>

2. color:顏色值。
示例:
<declare-styleable name = "名稱">

<attr name = "textColor" format = "color" />
</declare-styleable>

3. boolean:布爾值。
示例:
<declare-styleable name = "名稱">

<attr name = "focusable" format = "boolean" />
</declare-styleable>

4. dimension:尺寸值。
示例:
<declare-styleable name = "名稱">

<attr name = "layout_width" format = "dimension" />
</declare-styleable>

5. float:浮點值。
示例:
<declare-styleable name = "名稱">

<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />
</declare-styleable>

6. integer:整型值。
示例:
<declare-styleable name = "名稱">

<attr name = "frameDuration" format="integer" />
<attr name = "framesCount" format="integer" />
</declare-styleable>

7. string:字元串。
示例:
<declare-styleable name = "名稱">

<attr name = "text" format = "string" />
</declare-styleable>

8. fraction:百分數。
示例:

<declare-styleable name="名稱">
<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />
</declare-styleable>

9. enum:枚舉值。
示例:
<declare-styleable name="名稱">

<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>

10. flag:位或運算。
示例:
<declare-styleable name="名稱">

<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
</attr>
</declare-styleable>

11.多類型。
示例:

<declare-styleable name = "名稱">
<attr name = "background" format = "reference|color" />
</declare-styleable>

二、屬性的使用以及自定義控制項的實現
1、構思控制項的組成元素,思考所需自定義的屬性。
比如:我要做一個 <帶陰影的按鈕,按鈕正下方有文字說明>(類似9宮格按鈕)
新建values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="custom_view">
<attr name="custom_id" format="integer" />
<attr name="src" format="reference" />
<attr name="background" format="reference" />
<attr name="text" format="string" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>

以上,所定義為custom_view,custom_id為按鈕id,src為按鈕,background為陰影背景,text為按鈕說明,textColor為字體顏色,textSize為字體大小。

2、怎麼自定義控制項呢,怎麼使用這些屬性呢?話不多說請看代碼,CustomView :

package com.nanlus.custom;
import com.nanlus.custom.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomView extends FrameLayout implements OnClickListener {
private CustomListener customListener = null;
private Drawable mSrc = null, mBackground = null;
private String mText = "";
private int mTextColor = 0;
private float mTextSize = 20;
private int mCustomId = 0;
private ImageView mBackgroundView = null;
private ImageButton mButtonView = null;
private TextView mTextView = null;
private LayoutParams mParams = null;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.custom_view);
mSrc = a.getDrawable(R.styleable.custom_view_src);
mBackground = a.getDrawable(R.styleable.custom_view_background);
mText = a.getString(R.styleable.custom_view_text);
mTextColor = a.getColor(R.styleable.custom_view_textColor,
Color.WHITE);
mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
mTextView = new TextView(context);
mTextView.setTextSize(mTextSize);
mTextView.setTextColor(mTextColor);
mTextView.setText(mText);
mTextView.setGravity(Gravity.CENTER);
mTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView = new ImageButton(context);
mButtonView.setImageDrawable(mSrc);
mButtonView.setBackgroundDrawable(null);
mButtonView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mButtonView.setOnClickListener(this);
mBackgroundView = new ImageView(context);
mBackgroundView.setImageDrawable(mBackground);
mBackgroundView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mBackgroundView);
addView(mButtonView);
addView(mTextView);
this.setOnClickListener(this);
a.recycle();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mParams = (LayoutParams) mButtonView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mButtonView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mBackgroundView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mBackgroundView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mTextView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
mTextView.setLayoutParams(mParams);
}
}
public void setCustomListener(CustomListener l) {
customListener = l;
}
@Override
public void onClick(View v) {
if (customListener != null) {
customListener.onCuscomClick(v, mCustomId);
}
}
public interface CustomListener {
void onCuscomClick(View v, int custom_id);
}
}
代碼很簡單,就不多說,下面來看看我們的CustomView是怎麼用的,請看:

3、自定義控制項的使用
話不多說,請看代碼,main.xml:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal" >
<com.nanlus.custom.CustomView
android:id="@+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
nanlus:background="@drawable/background"
nanlus:custom_id="1"
nanlus:src="@drawable/style_button"
nanlus:text="按鈕1" >
</com.nanlus.custom.CustomView>
</LinearLayout>
</RelativeLayout>

在這里需要解釋一下,
xmlns:nanlus="http://schemas.android.com/apk/res/com.nanlus.custom"
nanlus為在xml中的前綴,com.nanlus.custom為包名

4、在Activity中,直接上代碼
package com.nanlus.custom;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.nanlus.BaseActivity;
import com.nanlus.custom.R;
import com.nanlus.custom.CustomView.CustomListener;
public class CustomActivity extends BaseActivity implements CustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
}
@Override
public void onCuscomClick(View v, int custom_id) {
switch (custom_id) {
case 1:
Toast.makeText(this, "hello !!!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}

熱點內容
壓縮內存軟體 發布:2025-01-31 16:51:39 瀏覽:145
腳本lcd 發布:2025-01-31 16:41:02 瀏覽:515
安卓selinux干什麼用的 發布:2025-01-31 16:32:04 瀏覽:531
俠盜獵車手加錢密碼是多少 發布:2025-01-31 15:44:28 瀏覽:662
沒密碼怎麼登微信 發布:2025-01-31 15:33:51 瀏覽:737
c語言死機程序 發布:2025-01-31 15:07:52 瀏覽:18
編程教育裝修 發布:2025-01-31 15:04:38 瀏覽:402
函數和存儲過程的區別 發布:2025-01-31 14:39:12 瀏覽:610
地下室柱子箍筋的加密 發布:2025-01-31 14:36:11 瀏覽:935
手機拍攝視頻在哪個文件夾 發布:2025-01-31 14:34:28 瀏覽:761