2016-03-03 93 views
0

所以,我有1個屏幕被切成兩部分。第一部分包含4個按鈕(紅色,藍色,綠色,紫色),第二部分是空白區域。 我想要的是,當我按下按鈕1時,我想要對應的顏色出現在空白處。點擊一個按鈕,並在屏幕的一半上改變顏色

如何創建和空空間

<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    android:weightSum="2" 
 
    android:orientation="vertical"> 
 

 
    <RelativeLayout 
 
     android:layout_width="match_parent" 
 
     android:layout_height="0dp" 
 
     android:layout_weight="0.5"> 
 
    <Button 
 
     android:layout_width="200sp" 
 
     android:layout_height="50sp" 
 
     android:id="@+id/button1" 
 
     android:text="Red"/> 
 

 

 
    <Button 
 
     android:layout_width="200sp" 
 
     android:layout_height="50sp" 
 
     android:id="@+id/button2" 
 
     android:layout_toRightOf="@+id/button1" 
 
     android:text="Blue"/> 
 
    <Button 
 
     android:layout_width="200sp" 
 
     android:layout_height="50sp" 
 
     android:id="@+id/button3" 
 
     android:layout_below="@+id/button1" 
 
     android:text="Green"/> 
 
    <Button 
 
     android:layout_width="200sp" 
 
     android:layout_height="50sp" 
 
     android:id="@+id/button4" 
 
     android:layout_toRightOf="@+id/button3" 
 
     android:layout_below="@+id/button2" 
 
     android:text="Purple"/> 
 
    </RelativeLayout> 
 

 
<RelativeLayout 
 
    android:layout_width="match_parent" 
 
    android:layout_height="0dp" 
 
    android:layout_weight="1.5" 
 
    android:id="@+id/bg2" 
 
    android:background="@drawable/selector"> 
 

 

 
</RelativeLayout> 
 
</LinearLayout>

+0

你做了一些Java類來做到這一點? –

回答

0

在你的onCreate添加

Button button1 = (Button)findViewById(R.id.button1); 
RelativeLayout rel =(RelativeLayout)findViewById(R.id.bg2); 
     button1.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      rel.setBackgroundColor(Color.RED);   
      } 
     }); 
+0

即時通知bg2和Color.Red –

+0

「符號無法解析」的錯誤噢,我的壞它是RED而不是紅色。而bg2假設是你的xml文件中給出的id。 也許你必須導入導入android.widget.RelativeLayout;並導入android.graphics.Color; –

+0

我已經導入了這兩個項目,而「bg2」仍然不適合... –

0

你應該在這個活動創建兩個片段,並創建一個米姆兩個部分介紹這兩個碎片按鍵之間的連接,所以這兩個片段可以通訊 然後你可以發送和接收兩個片段之間的數據

+0

不需要2個片段可以在1個片段中使用佈局完成 –

0

看看這個問題:

set background color: Android

你基本上遵循相同的步驟,除了你調用相應的setBackgroundColor(Color.parseColor( 「XYZ」)); 作爲按鈕的onClick()被調用時按鈕的顏色。

相關問題