博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自定义android控件
阅读量:2338 次
发布时间:2019-05-10

本文共 2215 字,大约阅读时间需要 7 分钟。

新建一个Android工程
保证下面的文件布局,标上了*号的是需要自己加上去的,代码马上贴出来
+userControl
+src
+blacklaw.product.usercontrol
-ImageBtn.java(自定义控件的类)*1-1
-MainActivity.java
+res
+drawable
-btn.xml(自定义控件的背景布局,可选)*2-1
+layout
-activity_main.xml
-imagebtn.xml(自定义控件的布局)*1-2
1-1自定义控件的类
package blacklaw.product.usercontrol;import android.content.Context;import android.util.AttributeSet;import android.view.LayoutInflater;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;public class ImageBtn extends LinearLayout {    private ImageView imageView;    private TextView  textView;    public ImageBtn(Context context) {        super(context);        // TODO Auto-generated constructor stub    }    public ImageBtn(Context context, AttributeSet attrs) {       super(context, attrs);        // TODO Auto-generated constructor stub        LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);	inflater.inflate(R.layout.imagebtn, this);	imageView=(ImageView) findViewById(R.id.imageView1);	textView=(TextView)findViewById(R.id.textView1);	}    /*** 设置图片资源*/ 	public void setImageResource(int resId) { 	imageView.setImageResource(resId);    }     /*** 设置显示的文字 */     public void setTextViewText(String text) {         textView.setText(text);     } }
1-2
自定义控件的布局
控件完成了,两步就行,一个是执行类,一个是布局的xml文件
接着讲一下控件的使用
在activity_main.xml的xml源中直接插入代码
如果需要背景图片的话就需要增加语句
变成
  
背景布局文件btn.xml如下
最后在mainActivity.class调用就行
public class mainActivity extends Activity {  private ImageBtn imageBtn1;   private ImageBtn imageBtn2;    @Override   protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub       super.onCreate(savedInstanceState);       setContentView(R.layout.identifybutton);        imageBtn1=(ImageBtn) this.findViewById(R.id.btn_right);        imageBtn1.setTextViewText("确定");       	imageBtn1.setImageResource(R.drawable.right_icon);	imageBtn1.setOnClickListener(new View.OnClickListener() {	public void onClick(View v) {                // TODO Auto-generated method stub                Toast.makeText(getApplicationContext(), "点击的正确按钮", 1).show();           }       });}}

转载地址:http://cngpb.baihongyu.com/

你可能感兴趣的文章
Palindrome Partitioning II
查看>>
Clone Graph
查看>>
Gas Station
查看>>
Candy
查看>>
Single Number
查看>>
SetForeGroundWindow
查看>>
判断程序执行用户和活动用户是否一致
查看>>
Com引起计数
查看>>
IHTMLDocument2 IE浏览器编程
查看>>
C/C++中指针和引用之相关问题研究
查看>>
一些AIX问题,自动logout
查看>>
AIX操作系统及HACMP群集系统安装步骤
查看>>
AIX资源监控与调制工具
查看>>
aix里面怎么查看实际的磁盘空间
查看>>
银行AIX日常维护内容
查看>>
AIX 安全命令
查看>>
AIX故障定位
查看>>
AIX运行级别介绍
查看>>
Linux zombie进程
查看>>
Linux 的僵尸(zombie)进程
查看>>