Android中自定义控件
16lz
2021-12-04
自定义了一个Button按钮,效果如图,有自定义背景(可根据文字长短扩展),自定义按钮图片和文字背景图片扩展,参考http://www.7747.net/kf/201104/88131.html 这个文章,http://blog.csdn.net/greatstar/archive/2010/10/12/5936177.aspx 和这个文章。使用draw9patch时遇到不能启动,原因是Android 2.3少了一个包,swing-worker-1.2 下载放在android-sdk\tools\lib 下遍可以正常使用。
其他直接上代码
?[Copy to clipboard] Download zuiniuwang.java
- <spanstyle="font-size:14px">importandroid.content.Context;
- importandroid.view.ViewGroup;
- importandroid.widget.ImageView;
- importandroid.widget.LinearLayout;
- importandroid.widget.RelativeLayout;
- importandroid.widget.TextView;
- publicclassMyViewTestextendsRelativeLayout{
- privatefinalintWC=LinearLayout.LayoutParams.WRAP_CONTENT;
- privatefinalintFP=LinearLayout.LayoutParams.FILL_PARENT;
- privatefinalstaticStringTAG=MyViewTest.class.getSimpleName();
- /**
- *
- *@paramcontext
- *@parambackgroudPic背景图片的ID为空则为默认
- *@paramimagePic按钮前面的图片为空则为默认
- *@paramtext按钮的文本为空则为默认
- */
- publicMyViewTest(Contextcontext,IntegerbackgroudPic,IntegerimagePic,Stringtext){
- super(context);
- //TODOAuto-generatedconstructorstub
- if(backgroudPic==null)
- this.setBackgroundResource(R.drawable.my_music_button);
- else
- this.setBackgroundResource(backgroudPic);
- ImageViewimageView=newImageView(context);
- if(imagePic==null)
- imageView.setImageResource(R.drawable.style1_button_icon_normal);
- else
- imageView.setImageResource(imagePic);
- imageView.setId(1);
- RelativeLayout.LayoutParamslp1=newRelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT);
- lp1.addRule(RelativeLayout.RIGHT_OF,1);
- TextViewtextView=newTextView(context);
- if(text==null)
- textView.setText("mycustombutton");
- else
- textView.setText(text);
- this.addView(imageView);
- this.addView(textView,lp1);
- }
- }
其中R.drawable.my_music_button 是一个XML文件,定义了按钮的选中点击等事件发生时,背景图片的变化,直接更改文件中相应的图片便可
?[Copy to clipboard] Download zuiniuwang.xml
- <spanstyle="font-size:14px"><?xmlversion="1.0"encoding="UTF-8"?>
- </span>
- <selectorxmlns:android="http://schemas.android.com/apk/res/android"><spanstyle="font-size:14px">
- </span><itemandroid:drawable="@drawable/my_button_bg"android:state_pressed="true"><spanstyle="font-size:14px">
- </span><itemandroid:drawable="@drawable/my_button_bg"android:state_focused="true"><spanstyle="font-size:14px">
- </span><itemandroid:drawable="@drawable/my_music_button_bg"><spanstyle="font-size:14px">
- </span></item></item></item></selector><spanstyle="font-size:14px">
- </span>
本文出自 “最牛傻蛋的博客” 博客,转载请与作者联系!
更多相关文章
- android 输入法弹出键盘把listview顶上去,保留顶部标题栏位置不动
- 系出名门Android(5) - 控件(View)之TextView, Button, ImageButt
- 关于visibility的属性值visible,invisible,gone的区别
- android的selector,背景选择器
- Android(安卓)关于RatingBar评分条
- android 单选按钮组的使用
- android 对话框AlertDialog
- android:动态创建多个按钮 并给每个按键添加监听事件
- Android_RadioGroup实现Tab