android自定义switch
① 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;
}
}
}