I have created a custom view name StepView . Here is the code for 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);
}
}
It is the code for 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>
Now I used the XML in main layout.
<?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>
I have cheched that it is appearing properly. But when I add the following code it is giving NullPointerException.
StepView stepMenu = (StepView) findViewById(R.id.stepMenu);
stepMenu.addStep("Picture", R.drawable.step01, null);
I have checked that stepMenu
is giving null.
Whatis the problem in my code?
You are not showing the full code block where you get the error, but it looks like you may have forgotten to use
setContentView(R.layout.main_layout);
to set the layout in use.I solved the prob...change the code in constructor of StepView Class