2017-03-13 15 views
0

レイアウトに2つのテキストビューを持つカスタムビューがあります。 1つをkeyとし、もう1つをvalueとしましょう。ツールのような振る舞い:カ​​スタム表示のテキスト?

だから、TextViewにはどのようなことが分かっていますか?私は例えば、私のカスタムビューと似た何かをしたい

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

<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のためにはそうのようなものです:

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> 

問題は、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

関連する問題