2017-03-13 13 views
0

레이아웃에 두 개의 텍스트보기가있는 사용자 정의보기가 있습니다. 하나는 key이고 다른 하나는 value입니다.도구와 비슷한 동작 : 사용자 정의보기의 텍스트?

그래서 너는 TextView이 이것을 어떻게 알아?

public MyCustomView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 
      .inflate(R.layout.my_custom_view, this, true); 

    key = (TextView) findViewById(R.id.key); 
    value = (TextView) findViewById(R.id.value); 

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0); 
    try { 
     if (isInEditMode()) { 
      key.setText(a.getText(R.styleable.MyCustomView_key_preview)); 
      value.setText(a.getText(R.styleable.MyCustomView_value_preview)); 
     } 
     key.setText(a.getText(R.styleable.MyCustomView_key)); 
     value.setText(a.getText(R.styleable.MyCustomView_value)); 
    } finally { 
     a.recycle(); 
    } 
} 

그리고 attrs.xml :

<declare-styleable name="MyCustomView"> 
    <attr name="key" format="string" /> 
    <attr name="key_preview" format="string" /> 
    <attr name="value" format="string" /> 
    <attr name="value_preview" format="string" /> 
</declare-styleable> 

<com.package.whatever.MyCustomView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:key_preview="Preview text for the key" 
    app:value_preview="Preview text for the value" /> 

MyCustomView의 생성자 그렇게 같다 :

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    tools:text="Preview text shown in the layout editor" /> 

나는 예를 들어, 내 사용자 지정보기와 유사한 무언가를하고 싶어

문제는 MyCustomView을 레이아웃 편집기에서 볼 때 isInEditMode()false을 반환한다는 것입니다. 내가 app:key="yay"을 추가하면 잘 작동하지만, app:key_preview="nay :("에 대해서는 아무 것도 나타나지 않습니다.

무엇을 제공합니까?

답변

1

나는 딩고이며 거짓말 쟁이다. isInEditMode()이 false를 반환하지 않았습니다.

기침 기침 :

if (isInEditMode()) { 
     key.setText(a.getText(R.styleable.MyCustomView_key_preview)); 
     value.setText(a.getText(R.styleable.MyCustomView_value_preview)); 
    } else { 
     key.setText(a.getText(R.styleable.MyCustomView_key)); 
     value.setText(a.getText(R.styleable.MyCustomView_value)); 
    } 

, 나는 처음에 있었다 app:key_preview의 값으로 키를 설정 사실은 무엇인지 밝혀 그러나 그것은 다음 이후에 반환 된 nulla.getText(R.styleable.MyCustomView_key) 것을 덮어 씁니다했다.

voopz.

+0

또는 if/else 문을 사용할 수 있습니다. 그건 깨끗해. – fsociety

+0

반영하도록 수정 됨 ^ – fsociety