怎么在Android中实现一个自定义控件
今天就跟大家聊聊有关怎么在Android中实现一个自定义控件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
创新互联从2013年开始,是专业互联网技术服务公司,拥有项目网站制作、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元海晏做网站,已为上家服务,为海晏各地企业和个人服务,联系电话:18982081108
首先定义一个layout实现按钮内部布局:
接下来写一个类继承LinearLayout,导入刚刚的布局,并且设置需要的方法,从而使的能在代码中控制这个自定义控件内容的显示。
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);
}
}在需要使用这个自定义控件的layout中加入这控件,只需要在xml中加入即可。
这里用到了背景图片 在drawable/btn.xml

最后在activity中设置该控件,和其他控件差不多:
public class IdentifyButtonActivity 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);
imageBtn2=(ImageBtn) this.findViewById(R.id.btn_error);
imageBtn1.setTextViewText("确定");
imageBtn2.setTextViewText("取消");
imageBtn1.setImageResource(R.drawable.right_icon);
imageBtn2.setImageResource(R.drawable.error_icon);
imageBtn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "点击的正确按钮", 1).show();
}
});
imageBtn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "点击的错误按钮", 1).show();
}
});
}
}最后看看我们自定义控件的效果吧!

看完上述内容,你们对怎么在Android中实现一个自定义控件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。
本文标题:怎么在Android中实现一个自定义控件
文章出自:http://www.jxjierui.cn/article/ppcphe.html


咨询
建站咨询
