Reputation: 3730
In my app I'm trying to create my own HorizontalScrollView that "snaps" when you swipe through the views inside of it. Everytime it tries to load the layout, it crashes. So, I'm taking baby steps. I'm new to creating custom views programmatically, so if there may be some "common sense" mistakes.
Here is my CustomView.java
file:
import android.content.Context;
import android.view.View;
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
}
Here is my MainActivity.java
file:
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
}
Here is my main_layout.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/lchoose_weapon"
tools:context=".ChooseWeaponActivity" >
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Title"
android:textSize="40sp" />
<com.javaknight.ultimaterps.CustomView
android:id="@+id/CustomVw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvTitle"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/CustomVm"
android:layout_centerHorizontal="true"
android:text="Another TextView Below" />
<Button
android:id="@+id/bOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv2"
android:layout_centerHorizontal="true"
android:text="ok" />
</RelativeLayout>
Using the following code fails to display the layout. As soon as I remove the CustomView from the xml file, it works fine. I want the xml layout file to have the Custom View inside of it.
Upvotes: 2
Views: 2649
Reputation: 69188
You should create all the constructors in your custom View:
public CusatomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
If you do it, I guess your layout will work.
Upvotes: 8