2014-12-02 32 views
0

鉴于这种布局命名relLayoutWrap.xml:Android的一套样式规则

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/RelativeLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 
    <TextView 
     android:id="@+id/priorityView" 
     android:layout_width="50dip" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/statusCheckBox" 
     android:layout_alignParentRight="true" 
     android:layout_alignTop="@+id/StatusLabel" > 
    </TextView> 
</RelativeLayout> 

我想不同的背景颜色应用到基于价值的相对布局父元素TextView元素。

textview元素的值可以随着我膨胀/回收视图而改变。即:

LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
RelativeLayout itemLayout = (RelativeLayout) inflater.inflate(R.layout.relLayoutWrap,null); 
final TextView priorityView = (TextView) itemLayout.findViewById(R.id.priorityView); 

priorityView.setText("yes"); //or sometimes "no" 

所以基本上如果TextView的值是“是”我希望RelativeLayouts背景色为黄色,如果它的“不”,我想背景颜色是蓝色。这可能是纯粹通过XML风格的规则?或者,我必须手动设置背景颜色,因为此值以编程方式更改?

回答

1

老实说,最好的方法是自己设置颜色。

据我所知,没有办法用XML来做到这一点,例如有条件地检查文本,然后根据文本更改颜色。你可能会有两种不同的XML按钮,然后这样做,但在这里并不需要。

在我的代码中,我有类似的东西,除了我有更多的东西要改变,而不仅仅是颜色。对我来说,我做这样的事情......

public static final int STATUS_CODE_YES = 1; 
public static final int STATUS_CODE_NO = 2; 

. . . 

if(something something something) { 
    //I need to set the state to Yes! 
    updateTextView(STATUS_CODE_YES); 
} else { 
    //I need to set the state to no... 
    updateTextView(STATUS_CODE_NO); 
} 

. . . 


public void updateTextView(int status) { 
switch(status) { 
    case STATUS_CODE_YES: 
     textView.setText("Yes"); 
     textView.setBackground(Color.YELLOW); 
     //a lot more stuff here 
     break; 
    case STATUS_CODE_NO: 
     textView.setText("No"); 
     textView.setBackground(Color.BLUE); 
     //a lot more stuff here 
     break; 
    default: 
     System.out.println("You did something wrong here...ERROR"); 
     break; 
} 

这个系统对我来说工作得很好。从技术上讲,我想有可能通过XML来做到这一点,但它们并不适用于这种情况。

+0

ahhh。被网站stylez宠坏了:'( 现在我觉得这很有道理。 – Rooster 2014-12-02 05:09:03