Button - Change background color on click

前端 未结 5 639
再見小時候
再見小時候 2021-02-03 10:48

I have 8 buttons in my activity. What I am looking for is, The buttons have a default background and when a button is clicked, the background color should change to some other c

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-03 11:26

    changing background color in layout when respective color button is clicked in android

    main_layout.xml

    
    
        

    MyActivity.java

    package ram.android.com.cwp1;
    
    import android.app.Activity;
    import android.graphics.Color;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    
    import com.google.android.gms.appindexing.Action;
    import com.google.android.gms.appindexing.AppIndex;
    import com.google.android.gms.common.api.GoogleApiClient;
    
    /**
     * Created by VENKATESH on 10-Jun-16.
     */
    public class MyActivity extends Activity implements View.OnClickListener {
        /**
         * ATTENTION: This was auto-generated to implement the App Indexing API.
         * See https://g.co/AppIndexing/AndroidStudio for more information.
         */
        Button r, g, b;
        LinearLayout ll;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);
            ll = (LinearLayout) findViewById(R.id.l1);
            r = (Button) findViewById(R.id.b1);
            g = (Button) findViewById(R.id.b2);
            b = (Button) findViewById(R.id.b3);
            r.setOnClickListener(this);
            g.setOnClickListener(this);
            b.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.b1:
                    ll.setBackgroundColor(Color.RED);
                    break;
    
                case R.id.b2:
                    ll.setBackgroundColor(Color.GREEN);
                    break;
                case R.id.b3:
                    ll.setBackgroundColor(Color.BLUE);
                    break;
    
            }
    
        }
    }
    

提交回复
热议问题