AndroidButton和ImageButton

mac2022-06-30  99

---恢复内容开始---

Button是一种按钮控件,用户能够在该控件上点击,并且引发相应的事件处理函数 ImageButton用以实现能够显示图像功能的按钮控件   实例: 建立一个“ButtonDemo”的程序,包含Button和ImageButton两个按钮,上方是Button按钮,下方是ImageButton控件   ButtonDemo在XML文件中的代码:                                                                                                      
<Button android:id="@+id/Button01"      android:layout_width="wrap_content"     android:layout_height="wrap_content" android:text="Button01"> <Button/>   <ImageButton android:id="@+id/Button01"      android:layout_width="wrap_content"     android:layout_height="wrap_content" android:text="Button01"> <ImageButton/>                                                                                                         
  定义Button控件的高度( android:layout_width="wrap_content")、宽度( android:layout_height="wrap_content")和内容(android:text="Button01")   定义ImageButton控件的高度( android:layout_width="wrap_content")、宽度(android:layout_height="wrap_content"),但是没定义显示的图像,在后面的代码中进行定义  
      引入资源 将download.png(图片)文件拷贝到/res/drawable文件夹下 在/res目录上选择Refresh,新添加的文件将无发找到资源的错误   在Activity类中更改Button和ImageButton内容 引入android.widget.Button和android.widget.ImageButton                                                                                                                                 
Button button = (Button)findViewwById(R.id.Button01); ImageButton imageButton = (ImageButton)findViewById(R.id.ImageButton01); button.setText("Button"按钮); imageButton.setImageResource(R.drawable.download);    
                                                                                                                         第一行代码用于引用在XML文件中定义的Button控件 第二行代码用于引用在XML文件中定义的ImageButton控件 第三行代码将Button的显示内容更改为“Button按钮” 第四行代码利用setImageResource()函数,将新加入的png文件R.drawable.download传递给ImageButton                                                                                                     按钮相应点击事件:添加点击事件的监听器  
                                                                                           final TextView textView = (TexrView)findViewById(R.id.TextView01); button.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ textView.setText("Button按钮"); } }); imageButton.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ textView.setText("ImageButton按钮"); } });                                                                                                       
第二行代码中button对象通过调用setOnClickListener()函数,注册一个点击(Click)事件的监听器View.OnClickListener() 第三行代码是点击事件的回掉函数 第四行代码将TextView的显示内容更改为"Button按钮"   运行结果:  

---恢复内容结束---

转载于:https://www.cnblogs.com/Emperor-lgx/p/4814240.html

最新回复(0)