温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中 Button如何使用

发布时间:2021-06-23 14:36:56 来源:亿速云 阅读:167 作者:Leah 栏目:移动开发

Android中 Button如何使用,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

一,Android Button布局管理(Layout)

每一个界面组件都是View的子类,都可以单独占用一个屏幕,但是真正的有用的界面都是这些组件的组合,在Android中都是用各种Layout来进行布局管理,这与传统的J2SE中的一些AWT,SWING界面方式基本相同,这里就不多说。

二,Android Button一个单独的界面元素:

在前面说到Hello World例子中,讲过这样一段代码。在Activity中.

public class HelloActivity extends Activity {  /** Called when the activity is first created. */  @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  TextView tv = new TextView(this);  tv.setText("Hello, World!");  this.setContentView(tv);  }  }

这里并没有用到Layout,这就是单独的组件方式。也可以改为:

super.onCreate(savedInstanceState);  Button btn = new Button(this);  btn.setText("TestButton");  this.setContentView(btn);

编译运行,会有一个全屏的Button,当然这不是你想要的实用的界面.那我们就用Layout来布局

super.onCreate(savedInstanceState);  Button btn = new Button(this);  btn.setText("TestButton");  Button btn2 = new Button(this);  btn2.setText("TestButton2");  LinearLayout layout = new LinearLayout(this);  layout.setOrientation(LinearLayout.VERTICAL);  layout.addView(btn);  layout.addView(btn2);  this.setContentView(layout);

编译运行,你就可以看到了两个上下排列的Android Button,当然对于布局管理器的使用,做过PC 上AWT,SWING的人都不陌生,这里就不赘述。

那如何响应事件呢: 大家猜一猜?想必大家不难猜到,在AWT中,在手机的J2ME中,都是用Listener 来处理事件响应,Android也未能脱俗。这与Blackberry,Symbian中的Observer是同一个道理。都是使用了设计模式的观察者模式。下面来看一个能响应事件的例子。

import android.app.Activity;  import android.os.Bundle;  import android.view.View;  import android.view.View.OnClickListener;  import android.widget.Button;  import android.widget.LinearLayout;  public class HelloActivity extends Activity implements OnClickListener {  Button btn = null;  Button btn2 = null;  public void onClick(View v) {   if (v == btn)  {  this.setTitle("You Clicked Button1");   }  if (v == btn2)  {  this.setTitle("You Clicked Button2");  }   }   @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  btn = new Button(this);  btn2 = new Button(this);  btn.setText("TestButton1");   btn2.setText("TestButton2");  btn.setOnClickListener(this);  btn2.setOnClickListener(this);  LinearLayout layout = new LinearLayout(this);  layout.setOrientation(LinearLayout.VERTICAL);  layout.addView(btn);  layout.addView(btn2);  this.setContentView(layout);   }  }

Android Button操作步骤是:

一,生成两个Button,配置Click事件监听者为HelloActivity ,此类实现了OnClickListener接口。

二,放入布局,按布局显示两个Button

三,按下其中一个Button,生成Click事件,调用HelloActivity 的OnClick接口函数。

四,对于View参数的值,判断是哪个View(Button)。改写Activity的Titile内容。注意,可别去对比View.getId(),缺省情况下,每个组件的Id值都为-1,除非人为设定Id值,用可视化编程时,为自动为其生成一个Id值。

关于Android中 Button如何使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI