2017-12-18 32 views
0

버튼의 텍스트 색상을 변경하기 위해 삼항 연산자를 사용하려고합니다. 다음과 같은 것이 있습니다. 여기에 XML이 있습니다.데이터 바인딩 설정 색상

<Button 
    android:id="@+id/actionButton" 
    android:layout_width="113dp" 
    android:layout_height="30dp" 
    android:background="@drawable/button" 
    android:backgroundTint="@{selected ? R.color.white : R.color.turquoise}" 
    android:text="@{selected ? &quot;Selected &quot; : &quot;Select &quot;}" 
    android:textColor="@{selected ? @color/white : @color/turquoise}" 
    android:onClick="@{(view) -> handler.selectClick(view)}"/> 

하지만 색상이 올바르게 설정되지 않았습니다. 나는 대신 약간의 사악한 보라색을 얻는다.

나는 같은 결과

<import type="com.myapp.R" /> 
android:textColor="@{selected ? R.color.white : R.color.turquoise}" 

을 시도했다.
어떻게해야합니까?

+0

당신은 청록색 색상 요 체크 않았다 올바른 색상 코드를 설정 했습니까? –

+0

예. 색상은 괜찮습니다. android : textColor = "@ color/turquoise"는 필요에 따라 작동합니다. – Shmuel

답변

0

첫 번째 변형은 정상적으로 작동합니다. this doc의 "리소스"장을 참조하십시오. 전체 작동 예제입니다.

colors.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    ... 
    <color name="foo">#fff</color> 
    <color name="bar">#000</color> 
</resources> 

main_activity.xml

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:android="http://schemas.android.com/apk/res/android"> 

    <data> 
     <variable name="selected" type="boolean" /> 
     <variable name="button2" type="String" /> 
    </data> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/btn_a" 
      android:onClick="switchColor" 
      android:text="Click me"/> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/btn_b" 
      android:textColor="@{selected ? @color/foo : @color/bar}" 
      android:text="@{button2}"/> 

    </LinearLayout> 
</layout> 

ActivityMain.class

public class ActivityMain extends AppCompatActivity { 

    public static final String TAG = "MainActivity"; 

    MainActivityBinding mBinding; 
    boolean mSelected; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mBinding = DataBindingUtil.setContentView(this, R.layout.main_activity); 
     mBinding.setButton2("Don't click me please!"); 
    } 

    public void switchColor(View view) { 
     mBinding.setSelected(mSelected = !mSelected); 
    } 
}