我正在尝试将CustomViewBeta(扩展的RelativeLayout)添加到CustomViewAlpha(扩展的LinearLayout)中-这个想法是,CustomViewAlpha将在ListView中容纳一堆CustomViewBeta。无论我尝试什么,都行不通。我要么什么都没看到-没有CustomViewBetas,或者当我在CustomViewBeta内部的一个TextView上尝试setText时,它给了我NPE
CustomViewAlpha可以很好地工作,因为它在Fragment的XML中进行了硬编码:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
...>
<com.path.CustomViewAlpha
android:id="@+id/customviewalpha"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
代码如下:
public class CustomViewAlpha extends LinearLayout {
private Context mContext;
public CustomViewAlpha (Context context) {
super(context);
this.mContext = context;
}
public CustomViewAlpha (Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
}
public CustomViewAlpha (Context context, AttributeSet attrs, int defStyle){
super(context, attrs,defStyle);
this.mContext = context;
}
public void addCustomViewBeta(String someString){
CustomViewBeta customViewBeta = new CustomViewBeta(mContext);
addView(customViewBeta);
}
未将CustomViewBeta硬编码在Fragment的XML中,并通过编程方式添加了:
公共类CustomViewBeta扩展了RelativeLayout {私有上下文mContext;
private TextView textView;
public CustomViewBeta (Context context) {
super(context);
this.mContext = context;
init();
}
public CustomViewBeta (Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
}
public CustomViewBeta (Context context, AttributeSet attrs, int defStyle){
super(context, attrs,defStyle);
this.mContext = context;
init();
}
private void init() {
LayoutInflater.from(mContext).inflate(R.layout.customviewbeta, null, false);
textView = (TextView) findViewById(R.id.tripleexpandablelistview_category_name);
textView.setText("ASDASDASDAD");
}
使用此XML:
<?xml version="1.0" encoding="utf-8"?>
<com.path.CustomViewBeta
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/customviewbeta_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</com.path.CustomViewBeta>
我通常会在“ textView.setText(“ ASDASDASDAD”);“上被NPE击中 行,因为TextView为null。有什么我想念的吗?我是否不应该尝试为CustomViewBeta扩充XML,而只是以编程方式进行处理(以编程方式逐一添加文本视图?)?谢谢。
你的初始化是错误的
private void init() {
LayoutInflater.from(mContext).inflate(R.layout.customviewbeta, null, false);
textView = (TextView) findViewById(R.id.tripleexpandablelistview_category_name);
textView.setText("ASDASDASDAD");
}
最后一个参数必须true
将添加TextView
到RelativeLayout.Also中ViewGroup
,该static inflate
方法具有一个方法,因此可以避免LayoutInflater.from(mContext)
,只需调用inflate(mContext, R.layout.customviewbeta, this);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句