2013-05-19 55 views
0

正如你在代碼中看到的,我有一個父按鈕的佈局。 我想改變bg。每次單擊按鈕時隨機選擇父佈局的顏色。 但是,我的父級佈局的findViewById(R.layout.activity_main)給出null,因爲setContentView(R.layout.activity_main)設置爲相同的佈局。 我不想創建另一個父佈局,並添加此佈局作爲其子,然後setContentView爲parentlayout,然後ffindViewById我的子佈局。Android的findViewById爲父佈局

這是活動類代碼:

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 
public void button1Click(View view) 
    {  
     EditText edittext1; 
     Button button1;  
     button1 = (Button) view; 
     button1.setBackgroundColor(Color.GRAY); 
     edittext1 = (EditText) this.findViewById(R.id.editText1); 
     edittext1.setText("Welcome !"); 
     RelativeLayout rlayout = (RelativeLayout) this.findViewById(R.layout.activity_main); 
     rlayout.setBackgroundColor(Color.rgb((int)Math.random()*10,(int)Math.random()*10,(int)Math.random()*10)); 

    } 

這是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" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:onClick="button1Click" 
     android:text="@string/button_click" /> 

    <EditText 
     android:id="@+id/editText1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:ems="15" 
     android:inputType="text" > 

     <requestFocus /> 
    </EditText> 

</RelativeLayout> 
+1

RelativeLayout的rlayout =((RelativeLayout的)按鈕1).getParent(); – Tarun

回答

4

添加ID父相對佈局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/activity_main" 
    ... 

    ... 
</RelativeLayout> 

然後改變

RelativeLayout rlayout = (RelativeLayout) this.findViewById(R.layout.activity_main); 

RelativeLayout rlayout = (RelativeLayout) this.findViewById(R.id.activity_main); 
+0

明白了,謝謝! :) – the13thdev