Я пытаюсь сослаться на родственный элемент управления через XML.
Чтобы объявить атрибут для ссылки на идентификатор из MyTextView:
<?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 — расширение элементов управления
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// calls MyTextView Ctor
View v = inflater.inflate(R.layout.fragment_example, container, false);
}
Конструктор класса MyTextView — во время надувания сделайте что-нибудь с указанным текстовым представлением:
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
}
}
}
в этом примере v
всегда null
. Я предполагаю, что во время инфляции макета элементы управления еще не добавлены. Еще одна вещь, которую следует отметить, это то, что это находится в Fragment
, поэтому это может быть причиной того, что я не могу найти представление в родительской активности.
Можно ли ссылаться на элемент управления из другого, подобного этому?