私はXMLを介して兄弟コントロールを参照しようとしています。 MyTextViewからIDを参照する属性を宣言するインフルエンザ中にコントロールを別のコントロールから参照する方法はありますか?
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="valueTextViewId" format="reference" />
</declare-styleable>
</resources>
fragment_example.xml - どのようにカスタム属性を使用するには:
<!-- Declare a "Title" text view that references a "Value" -->
<com.example.MyTextView
android:id="@+id/foo"
example:valueTextViewId="@id/bar"
... />
<!-- Depending on the "text" attribute of this "Value" textview -->
<!-- Do something within "Title" textview -->
<com.example.MyTextView android:id="@+id/bar" />
MyFragment.java - 膨張させますコントロール
は常にnull
である。この例では
public TextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.MyTextView);
int refId = a.getResourceId(R.styleable.MyTextView_valueTextViewId);
// Updated to use context
if (refId > -1 && context instanceof Activity) {
Activity a = (Activity)context;
View v = a.findViewById(refId);
// THE PROBLEM: v is null
if (v != null) {
// In my case, I want to check if the "Value" textview
// is empty. If so I will set "this" textColor to gray
}
}
}
: -
MyTextViewクラスのコンストラクタインフレ率の間には、参照先のTextViewで何かをします。私はレイアウトインフレの間、コントロールがまだ追加されていないと仮定します。注目すべきもう一つは、これはFragment
にあるということです。そのため、親アクティビティーでビューを見つけることができない可能性があります。
コントロールをこのような別のものから参照することはできますか?
これは面白くてスタートです。しかし、私は 'LayoutInflator'を使っているときに' mActivity'を渡すことはできません。 Ctorのコンテキスト属性がアクティビティ自体であるかどうかは私には分かりません。 –
それは可能です。 'if(context instanceof Activity)'でチェックし、 '((Activity)context)'をキャストしてください – r2DoesInc
おそらく、コンストラクタでそのロジックをしないでください。 'setActivityValue(mActivity)'のためにMyTextViewにメソッドを追加し、アクティビティが明示的に設定された後、他のテキストビューを隠すか操作するロジックを行います。 – r2DoesInc