我做了如下操作
1)创建可设置样式的
<declare-styleable name="Viewee">
<attr name="linkedView" format="reference"/>
</declare-styleable>
2)定义自定义视图布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffc0">
<TextView
android:id="@+id/custom_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="[text]"
/>
</LinearLayout>
3)创建必选类
public class Viewee extends LinearLayout
{
public Viewee(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
View.inflate(context, R.layout.viewee, this);
TextView textView = (TextView) findViewById(R.id.custom_text);
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.Viewee);
int id = typedArray.getResourceId(R.styleable.Viewee_linkedView, 0);
if (id != 0)
{
View view = findViewById(id);
textView.setText(((TextView) view).getText().toString());
}
typedArray.recycle();
}
}
最后,在下面这样的活动中
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.ns"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tvTest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="android"/>
<com.ns.Viewee
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:linkedView="@+id/tvTest"
/>
</LinearLayout>
现在,虽然我在Viewee构造器中收到了一个非零的id
,但findViewById(id)
返回了null并发生了NullPointerException
。
我遗漏了什么?
发布于 2012-06-15 06:14:09
我找到答案了!
问题出在findViewById(id)
和我所说的地方。findViewById
只查找子视图,而不是documentation所说的存在于较高层次结构级别的视图。所以我必须调用像getRootView().findViewById(id)
这样的东西,但这也会返回null
,因为我调用它的地方并不是corrent。
在Viewee
中,构造器Viewee
本身还没有附加到它的根,所以调用会导致NullPointerException
。
因此,如果我在构造之后调用其他地方的getRootView().findViewById(id)
,它工作得很好,并且"@+id/tvTest"
和"@id/tvTest"
都是正确的。我已经测试过了!
答案如下
public class Viewee extends LinearLayout
{
public Viewee(Context context, AttributeSet a)
{
super(context, attributeSet);
View.inflate(context, R.layout.main6, this);
TextView textView = (TextView) findViewById(R.id.custom_text);
TypedArray t = context.obtainStyledAttributes(a, R.styleable.Viewee);
int id = t.getResourceId(R.styleable.Viewee_linkedView, 0);
if (id != 0)
{
_id = id;
}
t.recycle();
}
private int _id;
public void Foo()
{
TextView textView = (TextView) findViewById(R.id.custom_text);
View view = getRootView().findViewById(_id);
textView.setText(((TextView) view).getText().toString());
}
}
当需要通过活动中其他地方的引用id处理附加的视图时,就会调用Foo
。
这完全归功于那些在this post中做出贡献的人。在提交问题之前,我没有看过这篇文章。
发布于 2012-06-15 03:16:53
您所描述的android:id
设置为app:linkedView="@+id/tvTest
。但是,@+id/tvTest
用于创建名为"tvTest“的新id。您想要做的是使用app:linkedView="@id/tvTest
。
https://stackoverflow.com/questions/11039829
复制相似问题