我创建了一个自定义视图名称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>
step.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
是否为空。我的代码有什么问题?
最佳答案
我解决了问题...在StepView类的构造函数中更改代码
public StepView(Context context, AttributeSet attrs) {
super(context, attrs);
....................
}