一、Button基本属性
1.普通按钮
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="CLICK"
android:background="#2196F3"
android:textColor="#ffffff"
android:shadowColor="#515151"
android:shadowDx="10"
android:shadowDy="10"
android:shadowRadius="10"></Button>
第二个按钮代码省略(复制粘贴即可),此时两个按钮重合了
2.线性布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" (垂直布局)
></LinearLayout>
然后将两个按钮放到LinearLayout标签里面
3.在MainActivity.java中
先添加继承implements
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
鼠标放在implements波浪线上,点击左下角的英文短语,出现onClick事件
@Override
public void onClick(View view) {
Toast.makeText(this, "广告时间", Toast.LENGTH_SHORT).show();
}
4.给Button加ID
<Button
android:id="@+id/btn1" (新增)
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="CLICK"
android:background="#2196F3"
android:textColor="#ffffff"
android:shadowColor="#515151"
android:shadowDx="10"
android:shadowDy="10"
android:shadowRadius="10"></Button>
<Button
android:id="@+id/btn2" (新增)
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="CLICK"
android:background="#2196F3"
android:textColor="#ffffff"
android:shadowColor="#515151"
android:shadowDx="10"
android:shadowDy="10"
android:shadowRadius="10"></Button>
5.给Button添加事件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
(新增) Button btn1=findViewById(R.id.btn1);
Button btn2=findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
6.运行
附:
@Override
public void onClick(View view) {
//Toast.makeText(this, "广告时间", Toast.LENGTH_SHORT).show();
switch (view.getId()){
case R.id.btn1:
//里面写点击后想要实现的效果
Toast.makeText(MainActivity.this,"按钮被点击",Toast.LENGTH_SHORT).show();
case R.id.btn2:
//里面写点击后想要实现的效果
Toast.makeText(MainActivity.this,"66666",Toast.LENGTH_SHORT).show();
}
}
二、Button的匿名内部类
1.简单布局一个Button
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Click"
android:shadowColor="#515151"/>
2.MainActivity.java里创建Button属性
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "CLICK", Toast.LENGTH_SHORT).show();}
});
}
}
3.运行