今天学习了通过两个按钮的点击监听事件。
private Button button1; private Button button2; private LinearLayout layout;
先声明按钮、布局LinearLayout
package com.example.cong.colorbutton; import android.graphics.Color; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { private Button button1; private Button button2; private Button button3; private LinearLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1= (Button) this.findViewById(R.id.button1); button2= (Button) this.findViewById(R.id.button2); button3= (Button) this.findViewById(R.id.button3); layout= (LinearLayout) this.findViewById(R.id.layout); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layout.setBackgroundColor(Color.RED); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layout.setBackgroundColor(Color.BLUE); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layout.setBackgroundColor(Color.GREEN); } }); } }
以下是xml的代码
在这里需要注意的是要明确LinearLayout的ID
android:id=“@+id/layout”
实现出来就是点哪个按钮,背景就变什么色。