前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ImageButton与Button

ImageButton与Button

作者头像
水击三千
发布2018-02-27 17:09:21
1.1K0
发布2018-02-27 17:09:21
举报
文章被收录于专栏:水击三千水击三千

1.Button控件

Butotn控件,主要用来实现一些命令操作,通过注册监听事件来实现。首先需要在xml文档中放入一个button按钮。

代码语言:javascript
复制
1     <Button
2         android:id="@+id/button1"
3         android:layout_width="180dp"
4         android:layout_height="64dp"
5         android:layout_x="45dp"
6         android:layout_y="269dp"
7         android:background="@drawable/btn01"
8         android:text="Button" />

可以在xml 中设置该控件的相关属性,包括layout_width等。后台实现的代码为

代码语言:javascript
复制
 1 public class MainActivity extends Activity {
 2 
 3     Button myButton;
 4     ImageButton myImg;
 5     TextView textView;
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_main);
10         myButton=(Button)findViewById(R.id.button1);
11         textView=(TextView)findViewById(R.id.text1);
12         myButton.setOnClickListener(new OnClickListener(){
13 
14             @Override
15             public void onClick(View v) {
16                 // TODO 自动生成的方法存根
17                 textView.setText("wo lai le");
18             Toast.makeText(MainActivity.this, "别惦记我", 5000).show();
19             }});
20     }
21 
22 
23     @Override
24     public boolean onCreateOptionsMenu(Menu menu) {
25         // Inflate the menu; this adds items to the action bar if it is present.
26         getMenuInflater().inflate(R.menu.main, menu);
27         return true;
28     }
29     
30 }

这里通过findViewById()来获取该button控件,为该控件实现setOnClickListener()方法,该方法可以响应button的单击事件。Toast.makeText()来实现弹出提示语言。

2、ImageButton控件

ImageButton控件,可以作为button的另外一种扩展,他可以drawable中显示图标。

ImageButton控件的注册。

代码语言:javascript
复制
1     <ImageButton
2         android:id="@+id/imageButton1"
3         android:layout_width="60dp"
4         android:layout_height="wrap_content"
5         android:layout_x="86dp"
6         android:layout_y="145dp"
7         android:background="@drawable/easyicon_net_24"
8         android:src="@drawable/imgbutton" />

可以在注册的时候,设置该控件的各种属性。

本文实现的主要是ImageButton控件的状态改变的时候,变换不同的图片。当鼠标单击的时候显示不同的图片。我们需要在drawable文件夹中加入一个xml文档。

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/easyicon_net_24" android:state_pressed="false"></item>
<item android:drawable="@drawable/syicon_net_24" android:state_pressed="true"></item>
</selector>

该文档用来注册imagebutton的不同状态,通过设置android:state_pressed的属性来实现。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-06-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档