完成如图所示的功能效果,点击按钮更改按钮上文字的颜色。
color_exchange(activity)
package com.example.myapplication_one;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class color_exchange extends AppCompatActivity {
Button button1,button2,button3,button4;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color_exchange);
init();
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setTextColor(Color.parseColor("#ff0000"));
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setTextColor(Color.parseColor("#0000ff"));
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setTextColor(Color.parseColor("#00ff00"));
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setTextColor(Color.parseColor("#ffff00"));
}
});
}
private void init(){
button1=findViewById(R.id.button3);
button2=findViewById(R.id.button4);
button3=findViewById(R.id.button5);
button4=findViewById(R.id.button6);
textView=findViewById(R.id.textView7);
}
}
color_exchange.xml
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Hello world!"
android:textSize="50dp"
android:layout_marginLeft="-90dp"/>
<Button
android:id="@+id/button3"
android:layout_below="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="红" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
android:layout_weight="1"
android:text="蓝" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
android:layout_weight="1"
android:text="绿" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button5"
android:layout_marginTop="4dp"
android:layout_weight="1"
android:text="黄" />
</RelativeLayout>
结果: