我创建了一个自定义视图名称StepView。这是 StepView 的代码。
public class StepView extends LinearLayout {
private Context cont;
private LinearLayout stepHolder;
public StepView(Context context, AttributeSet attrs) {
super(context);
// TODO Auto-generated constructor stub
LayoutInflater.from(context).inflate(R.layout.stepview, this, true);
stepHolder = (LinearLayout) findViewById(R.id.stepHolder);
cont = context;
}
public void addStep(String title, int drawableId, View.OnClickListener stepAction){
View step = LayoutInflater.from(cont).inflate(R.layout.step, this, true);
TextView txtText = (TextView) step.findViewById(R.id.txtText);
ImageView imgStep = (ImageView) step.findViewById(R.id.imgStep);
txtText.setText(title);
imgStep.setImageResource(drawableId);
stepHolder.addView(step);
}
}
它是 stepview.xml 的代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/stepHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
步骤.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imgStep"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtText">
</TextView>
</LinearLayout>
现在我在主布局中使用了 XML。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
..................
</LinearLayout>
<com.orthokeys.view.StepView
android:id="@+id/stepMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</com.orthokeys.view.StepView>
</merge>
我已经确认它显示正确。但是当我添加以下代码时,它给出了 NullPointerException。
StepView stepMenu = (StepView) findViewById(R.id.stepMenu);
stepMenu.addStep("Picture", R.drawable.step01, null);
我已经检查过它stepMenu
是空的。
我的代码有什么问题?