2014-05-07 57 views
0

想知道有沒有人遇到過這個問題。我有一個應用程序,它可以檢測臉部,並在臉部周圍放置可觸摸的方塊,全部放在RelativeLayout中。當我感動時,我想添加一些文本到視圖中,這很好用,但是當我去簡單地向TextView添加背景時,它什麼也不做。我試過了一個標準背景setBackgroundColor(Color.WHITE);,而不是我真正想要使用的背景(setBackgroundResource(R.drawable.nametag);),而且什麼也沒有。Android TextView無法設置背景顏色或可繪製

TextView nameLabelView = new TextView(activity); 
nameLabelView.setText(fullname); 
nameLabelView.setTextColor(Color.BLACK); 
nameLabelView.setBackgroundColor(Color.WHITE);     //TODO <-- wth?? 
//nameLabelView.setBackgroundResource(R.drawable.nametag); 
nameLabelView.setGravity(Gravity.CENTER_HORIZONTAL); 

//duplicate layout params from active face View so label sits inside it 
ViewGroup.LayoutParams lp = selectedFaceView.getLayoutParams(); 
nameLabelView.setLayoutParams(lp); 
facePreviewLayout.addView(nameLabelView); 

奇怪的是,希望這是顯而易見的人在那裏,在此先感謝!

回答

1

我測試了你的代碼,它對我來說工作正常。有必要提供更多信息,以便我可以幫助更多。下面的代碼工作正常。

MainActivity.java

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     TextView nameLabelView = new TextView(getApplicationContext()); 
     nameLabelView.setText("Test"); 
     nameLabelView.setTextColor(Color.WHITE); 
     nameLabelView.setBackgroundColor(Color.BLACK);     //TODO <-- wth?? 
     //nameLabelView.setBackgroundResource(R.drawable.nametag); 
     nameLabelView.setGravity(Gravity.CENTER_HORIZONTAL); 

     //duplicate layout params from active face View so label sits inside it 
     FrameLayout selectedFaceView = (FrameLayout)findViewById(R.id.frame_layout); 
     ViewGroup.LayoutParams lp = selectedFaceView.getLayoutParams(); 
     nameLabelView.setLayoutParams(lp); 
     RelativeLayout facePreviewLayout = (RelativeLayout)findViewById(R.id.relative_layout); 
     facePreviewLayout.addView(nameLabelView); 

    } 

} 

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/relative_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <FrameLayout 
     android:id="@+id/frame_layout" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:background="#00FF00" > 
    </FrameLayout> 

</RelativeLayout> 
0

謝謝janzoner您的測試真的很感激,好知道我是不是要瘋了。儘管我找到了解決這個問題的方法,但我不知道爲什麼這種方法能夠工作,而且我之前的設置沒有,也許我一直在盯着它太久而錯過了別的地方。

基本上我之前把名字標籤TextView加入主RelativeLayout(其子女是實際的圖像和所有的臉Views等)。

現在我已經將名稱標籤TextView轉移到它自己的RelativeLayout中,它位於臉部周圍,這很神奇地完成了這個訣竅。無論如何,這是一種更乾淨的做事方式,因爲您無法遍歷Views的小孩Views,但您可以登錄RelativeLayout的孩子,我將在稍後需要此操作!

唷!

+0

還有很多改進的空間:) – janzoner