2011-10-17 21 views
3

我設置textview背景等於透明,現在我想在代碼中改變它的背景。 當點擊mybtn(這是一個按鈕)改變textview背景,它是怎麼做到的?如何在代碼中設置textview的背景?

代碼:

Button btn = (Button) findViewById(R.id.btn_dialog); 
btn.setBackgroundColor(color.transparent); 
btn.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
    TextView txt = (TextView) findViewById(R.id.txt); 
    txt.setBackgroundColor(??????); 

    Toast.makeText(getBaseContext(), "this test is ok!", Toast.LENGTH_SHORT).show(); 
    } 
}); 

回答

7

您可以設置任何顏色使用這個:

txt.setBackgroundColor(Color.parseColor("#BABABA")); // set any custom color as background color 

txt.setBackgroundColor(Color.RED); // set default RED color as background color 
14

不使用setBackgroundDrawable但使用::

@Override 
    public void onClick(View v) { 
    TextView txt = (TextView) findViewById(R.id.txt); 
    txt.setBackgroundResource(R.drawable.textview_logo); 

    Toast.makeText(getBaseContext(), "this test is ok!", Toast.LENGTH_SHORT).show(); 
    } 
}); 

確保textview_logo是留在繪製文件夾

爲集背景:

txt.setBackgroundColor(Color.RED); 
+0

原諒我,我編輯我的代碼 由於我瓦納setBackgroungColor我的TextView 請幫我 –

+0

+1準確的解決方案,用於設置背景圖片。 –

+0

@PareshMayani感謝所有..。 。 –

1

有3個設置背景的duntiond。

txt.setBackgroundResource(int rsid); 
txt.setBakgroundDrawable(Drawable object); 
txt.setBackgroundColor(color id); 

最適合的是 txt.setBackgroundResource(INT RSID);在這裏你可以直接設置從下面繪製文件夾中的圖片:

txt.setBakgroundResource(R.drawable.image_name); 
0

如果您需要的顏色indentify你應該使用:

txt.setBackgroundColor(R.color.someColorInColorsXML); 

txt.setBackgroundDrawable(new ColorDrawable(AARRGGBB)); 
相關問題