【问题标题】:Button link with color change in android studioandroid studio中颜色变化的按钮链接
【发布时间】:2015-11-10 08:38:49
【问题描述】:

我正在开发我的应用程序,该应用程序即将完成,我想实现一个功能,用户可以单击按钮,背景会改变颜色。我该怎么办?我想要两个相邻的按钮,当单击时更改背景颜色。按钮一会将其更改为颜色,或者按钮二会将其更改为颜色二。我尝试对其进行编码,但它并没有以我想要的方式显示,所以我在这里问,因为我想再次从头开始按钮。

谁能帮我解决这个问题?

【问题讨论】:

  • 发布您的尝试,以便我们帮助您找出您做错了什么。否则,这篇文章对 SO 来说太宽泛了
  • 检查this thread将该代码放入按钮点击监听器

标签: android button colors background onclick


【解决方案1】:

您可以按如下方式更改活动本身的背景颜色:

这是活动的 XML 文件:-

<RelativeLayout 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"
    tools:context=".MainActivity"
    android:id="@+id/backgroundId">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RED"
        android:id="@+id/redButton"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="70dp"
        android:onClick="onRedButtonClick"/>
        </RelativeLayout>

这是java代码:

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onRedButtonClick(View view) {
        RelativeLayout background = (RelativeLayout) findViewBy(R.id.backgroundId);
        background.setBackgroundColor(Color.RED);
    }

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2022-01-02
    • 2021-10-04
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多