android基础-Button

来源:互联网 发布:java linux服务器 下载 编辑:程序博客网 时间:2024/06/05 02:23

对于button这个控件相信大家都很熟悉了吧!对于Qt的话有QPushButton,QToolButton,但是很清楚,对于Button我们需要他的单击事件,然后通过它的单击事件做我们想做的事情,因此我们很多时候都是对于它的单击事件做出相对于的处理来满足我们的需求!当然对于它的美观我们也是很有必要对它负责的!

对于Qt我们通过QPushButton单击的时候会发出个Clicked()的信号,然后通过连接信号和槽来做处理,而在android中我们没有信号,但是我们有监听器来监听用户的对于button控件的动作,然后做出相对应得处理!

ok!废话不多说,直接上代码!

这里用俩种方法来处理Button的单击的处理函数

1.监听器

首先在xml文件中定义button的id

<Button

android:id="@+id/login_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="登录";

android:textSize="18sp"/>

然后在相对于的java文件里

Button button = (Button)findViewById(R.id.login_button);//通过id来找控件

button.setOnClickLinstener(new Button.OnClickLinstener(){

public void onClick(View v){

//提示控件,第一个参数为content,第二个为显示文本,第三个为显示的时间

Toast.makeText(getApplicationContent,"按钮被单击啦!",Toast.LENGTH_LONG).show();

}

});


2.xml文件

对于xml文件中,直接可以通过xml中对Button的描述中来进行

<Button

android:id="@+id/login_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="登录";

android:textSize="18sp"

android:onClick="onButtonClick"

/>


然后再相对于的java文件中将该处理函数进行相对于的处理就可以啦!

public void onButtonClick(View v)

{

Log.v("loginactivity","按钮被单击啦!");

}

3,界面优化

对于button我们也需要在不同的状态的是有不同的显示背景,因此我们需要在不同状态的时候对Button的background进行一些相对应的改变这就是我们的需求

首先新建一个文件夹drawable,然后再这个文件夹中增加一个xml文件btn_style.xml

<?xml version="1.0" encoding="utf-8"?>

<selector>

<item android:state_focused="true" android:drawable="@drawable/btn_style_focus"/>

<item android:state_pressed="true android:drawable="@drawable/btn_style_press"/>

<item android:state_enabled="true" android:drawable="@drawable/btn_style_nomal"/>

</selector>


然后再布局的xml下为Button添加

android:background="@drawable/btn_style"

这样就ok啦!


0 0
原创粉丝点击