一、效果展示
二、实现步骤
1.xml页面布局
首先整体使用一个垂直方向的线性布局,第一行设置一个水平方向的线性布局。
对于第一行,两个按钮均分水平宽度,我们可以设置。
android:layout_width="0dp"
android:layout_weight="1"
两个按钮都这样设置,这样那两个按钮就均分宽度了。
然后禁用按钮的属性是:android:enabled="true/false"
按钮默认英文单词是大写,我们可以设置为小写:android:textAllCaps="false"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/enable"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="启用按钮start"
/>
<Button
android:id="@+id/disable"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="禁用按钮start"
/>
</LinearLayout>
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:enabled="false"
android:text="按钮start"
/>
</LinearLayout>
2. java代码
只需要简单的设置三个按钮的监听事件,对于一个界面有多个按钮需要监听的时候,最好直接让当前类实现View.OnClickListener, 重写onClick方法 然后多个按钮都可以使用。
因为调用的是同一个监听事件,所以需要判断是哪个按钮调用。我们可以通过id属性来区分多个按钮。
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.helloworld.util.DateUtil;
public class MainActivity extends Activity implements View.OnClickListener {
Button start;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enable=findViewById(R.id.enable);
Button disable=findViewById(R.id.disable);
start=findViewById(R.id.start);
enable.setOnClickListener(this); //设置监听事件
disable.setOnClickListener(this);
start.setOnClickListener(this);
}
@Override
public void onClick(View v) { //重写方法
switch (v.getId()) //通过id判断是哪个按钮被点击
{
case R.id.enable:
start.setEnabled(true);break;
case R.id.disable:
start.setEnabled(false);break;
case R.id.start:
Toast.makeText(this, DateUtil.getNowTime()+"按钮被点击", Toast.LENGTH_LONG).show();
}
}
}