I'm really curious about constructors for custom views. Currently I have one which extends the RelativeLayout. Each view need context for initialization. So, I put super() in the constructor. Although, I need the activity in my class so I took context from it. As far as I know, activity is a context too so why Android Studio gives me an inspection that I am missing the constructor with context ? My class looks like this:
public class CustomView extends RelativeLayout {
private Activity activity;
public CustomView(Activity activity) {
super(activity.getApplicationContext());
this.activity = activity;
initialize(activity.getApplicationContext());
}
//initialize method
}
This is the exact message Android Studio gives me:
Custom view CustomView is missing constructor used by tools: (Context) or (Context,AttributeSet) or (Context,AttributeSet,int)
Should I ignore this or should I pass in constructor both: activity and context?
Thanks for all information!
Better pass Context instead of Activity, because its possible to call View with Context but without Activity. For example if you call Dialog from Service.
Also based on documentation there is only one constructor is really necessary. But that constructor has contain AttributeSet as argument.
In your case it should looks like
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
this.activity = (Activity) context; //better to hold context actually
initialize(context);
}
And for sure good practice is to use all available constructors
I have created a public class in my main activity e.g.:
public class ActivityMain extends FragmentActivity {
// ...
public class MyClass extends Something implements SomethingListener{
public MyClass(Context context) {
super(context);
}
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyClass(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// Listener overrides
}
}
And I use it in my layout xml like:
<my.package.ActivityMain.MyClass
app:pstsShouldExpand="true"
//parameters
/>
That way I get a ClassNotFoundException just on the setContentView(R.layout.my_layout) line in Activity's onCreate().
Also the xml design editor on Android Studio complains about this class:
Exception Details java.lang.NoSuchMethodException:
my.package.ActivityMain$MyClass.<init>(android.content.Context, android.util.AttributeSet)
If I used in the xml the class which I extend, all render good. E.g:
xml:
<external.package.Something
android:id="#+id/object"
app:pstsShouldExpand="true"
//parameters
/>
ActivityMain:
Something something = (Something) findViewById(R.id.object)
something.setSomethingListener(new SomethingListener( ... ))
Of course the above solves this issue but is it possible to use a class created in an Activity in my XML?
Update:
The Something class has custom attributes e.g. app:pstsShouldExpand="true" not sure if they are passed down to it from my MyClass. It might be the issue.
I have a compound control that needs to access the Application object. My control extends LinearLayout, so because it isn't an Activity I can't call getApplication(). Is there a way I can do this from a Layout/View or pass the Application in?
There are a couple of things you could be depending on what you need the Application object for.
If you need the specific application instance, you could try casting your Context object to an Activity:
public class MyLinearLayout extends LinearLayout {
private Application mApplication;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
//As this is a custom ViewGroup, Context will be an Activity, but just to make sure..
if(context instanceof Activity)
mApplication = ((Activity) context).getApplication();
else
throw new IllegalArguementException("Context must be an Activity");
}
}
The code above checks to make sure that the Context passed to your custom view is an Activity, but in reality this should always be the case.
If you only need your Application object to use as a `Context', then you can call the 'context.getApplicationContext()' method:
public class MyLinearLayout extends LinearLayout {
private Context mAppContext;
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mAppContext = context.getApplicationContext();
}
}
You have to pass the Context in Constructor when you call My Control Class.
Hello i have a problem with the elimination of NullEx ...
I set mContext = context and now i have errors:
Implicit super constructor LinearLayout() is undefined. Must explicitly invoke another constructor
Constructor call must be the first statement in a constructor
public DigitalClock(Context context) {
mContext=context;
this(context, null);
}
Earlier thread Android alarm Clock which shows problem.
You need a superclass constructor call.
public DigitalClock(Context context) {
super(context); // Add a line like this.
// Consult constructor documentation for correct usage.
this(context, null); // this line must also be at the top.
mContext=context;
}
I would assume that you are extending View, in that case you need at least two constructors.
//...Override Constructors...
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DigitalClock(Context context){
super(context);
}
See if that helps.
I am building an Android application that uses the custom-built TwoDScrollView found here:
http://blog.gorges.us/2010/06/android-two-dimensional-scrollview/
This same class can be found referenced at several other websites, and others on Stack Overflow have asked questions with regard to it. I was using it in a previous Android application that I was building using Java/Eclipse, and I was having success.
With my current application, I wanted to use C# and MonoDroid. I decided to rewrite the entire TwoDScrollView class in C#. After rewriting it, and then using it in some layout XML, I get the following exceptions when trying to run my code:
System.NotSupportedException has been thrown. Unable to activate
instance of type MyProject.TwoDScrollView from native handle 44f4d310.
System.Exception: No constructor found for
MyProject.TwoDScrollView::.ctor(System.IntPtr,
Android.Runtime.JniHandleOwnership) ......with more text that
follows....
My layout XML is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<myproject.TwoDScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</myproject.TwoDScrollView>
</RelativeLayout>
Per the instructions at the following link on using custom views in layout XML in MonoDroid: http://docs.xamarin.com/android/advanced_topics/using_custom_views_in_a_layout
The constructors to the TwoDScrollView class look as follows:
public TwoDScrollView(Context context)
: base(context)
{
initTwoDScrollView();
}
public TwoDScrollView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
initTwoDScrollView();
}
public TwoDScrollView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
initTwoDScrollView();
}
The same constructors exist in the C# version as in the Java version (which you can find at the above link). Any idea on what could be going wrong? I can post the full C# code of my TwoDScrollView if anyone would like to see it. It's essentially the same as the Java code bit for bit - except rewritten in C#.
Thanks for any help!
Congratulations! You've hit a leaky abstraction. :-/
The problem is this: for better or worse, virtual method calls from constructors invoke the most derived method implementation. C# is the same as Java in this respect; consider the following program:
using System;
class Base {
public Base ()
{
Console.WriteLine ("Base..ctor");
M ();
}
public virtual void M ()
{
Console.WriteLine ("Base.M");
}
}
class Derived : Base {
public Derived ()
{
Console.WriteLine ("Derived..ctor");
}
public override void M ()
{
Console.WriteLine ("Derived.M");
}
}
static class Demo {
public static void Main ()
{
new Derived ();
}
}
When run, the output is:
Base..ctor
Derived.M
Derived..ctor
That is, the Derived.M() method is invoked before the Derived constructor has executed.
In Mono for Android, things get more...complicated. The Android Callable Wrapper (ACW)'s constructor is invoked by Java and is responsible for creating the peer C# instance and mapping the Java instance to the C# instance. However, if a virtual method is invoked from the Java constructor, then the method will be dispatched before there is a C# instance to invoke the method upon!
Let that sink in a bit.
I don't know which method is triggering the scenario for your specific code (the code fragment you provided works fine), but we do have a sample which hits this scenario: LogTextBox overrides the TextView.DefaultMovementMethod property, and the TextView constructor invokes the getDefaultMovementMethod() method. The result is that Android tries to invoke LogTextBox.DefaultMovementMethod before a LogTextBox instance even exists.
So what does Mono for Android do? Mono for Android created the ACW, and thus knows which C# type the getDefaultMovementMethod() method should be delegated to. What it doesn't have is an instance, because one hasn't been created. So Mono for Android creates an instance of the appropriate type...via the (IntPtr, JniHandleOwnership) constructor, and generates an error if this constructor cannot be found.
Once the (in this case) TextView constructor finishes executing, the LogTextBox's ACW constructor will execute, at which point Mono for Android will go "aha! we've already created a C# instance for this Java instance", and will then invoke the appropriate constructor on the already created instance. Meaning that for a single instance, two constructors will be executed: the (IntPtr, JniHandleOwnership) constructor, and (later) the (Context, IAttributeSet, int) constructor.
The error message says:
System.Exception: No constructor found for MyProject.TwoDScrollView::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership)
Try adding a constructor like it says and see if that helps:
public TwoDScrollView (IntPtr a, JniHandleOwnership b) : base (a, b)
{
}
I had the same problem with a custom imageview and the answer for jpobst certainly fixed the problem completely :
public CircularImageView(Context context)
:base(context)
{
init (context, null, 0);
}
public CircularImageView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
init (context, attrs, Resource.Attribute.circularImageViewStyle);
}
public CircularImageView(Context context, IAttributeSet attrs, int defStyle)
:base(context, attrs, defStyle)
{
init(context, attrs, defStyle);
}
public CircularImageView (IntPtr a, JniHandleOwnership b) : base (a, b)
{
}
I was using custom list view renderer, but none of the work arounds worked for me. But delaying the base.Dispose method helped me fix the crash, probably this gives the mono android, the chance to initialize the proxy instance.
Xamarin.Forms.Device.BeginInvokeOnMainThread(base.Dispose);
I don't see any crashes now!