2011-12-08 66 views
1

我有一些代碼創建一個RelativeLayout並添加一個按鈕。當從onCreate()創建時,它會很好地顯示紅色背景上的藍色按鈕。爲什麼我添加按鈕時,RelativeLayout背景會變黑?

但是,當點擊第一個新的按鈕在黑色背景上顯示時創建新的ReltativeLayout,所以我的RelativeLayout不顯示。

有趣的是,如果我註釋掉添加按鈕的行,它會起作用,所以不知何故按鈕正在影響相對佈局。

感謝您的任何幫助。

package com.android.mikeviewtester; 

import android.app.Activity; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.RelativeLayout; 

public class ViewTesterActivity extends Activity { 

    void createNewView(int bgColor, int btnColor) { 

     // create a new relative layout 
     android.widget.RelativeLayout newView = new android.widget.RelativeLayout(this); 

     // create a button 
     Button btn = new Button(this); 

     // set the background color 
     btn.setBackgroundColor(btnColor); 

     // create a layoutParams struct for adding the button to the relative layout view 
     ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(100, 100); 

     // add the button to the relative layout 
     newView.addView(btn, params); 

     // set the relative layout background color 
     newView.setBackgroundColor(bgColor); 

     // set the ontouch listener for the relativeLayout 
     newView.setOnTouchListener((android.view.View.OnTouchListener) mOnTouchListener); 

     // create the layout to fill the activity 
     RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); 

     // set the relative layout as the view 
     setContentView(newView, viewParams); 
    } 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // create and set the initial view 
     createNewView(Color.RED, Color.BLUE); 
    } 

    // ios - (void)buttonWasPressed:(id)whichButton { 
    private android.view.View.OnTouchListener mOnTouchListener = new android.view.View.OnTouchListener() { 
     public boolean onTouch(View v, MotionEvent event) { 

      if (v != null) 
       v.onTouchEvent(event); 

      if (event.getAction() == MotionEvent.ACTION_UP) { 

       // create and set a new view 
       createNewView(Color.GREEN, Color.MAGENTA); 
      } 

      return true; 
     } 
    }; 
} 
+0

前添加v.setVisibility(View.GONE);嘗試viewParams設置爲您的RelativeLayout,而不是在的setContentView() – Cata

回答

2

請在你的代碼的改變,即調用createNewView(Color.GREEN, Color.MAGENTA);

+0

這工作設置它,謝謝! – SkolVikingsGuy

+0

對不起,我現在在真實世界的代碼中看到它不起作用,因爲我沒有使用硬編碼大小(500x500),而是使用FILL_PARENT。您的修補程序適用於500x500,但不適用於FILL_PARENT。我編輯了上面的代碼。你能否解釋爲什麼你的建議解決了這個問題可以幫助我回答我自己的問題。謝謝。 – SkolVikingsGuy

+0

首先接受回答 – user493244

相關問題