I'm trying to extend Spinner
Android class in my code to implement a new function, but for some reason this didn't work.
This is the extended class:
import android.content.Context;
import android.widget.AdapterView;
import android.widget.Spinner;
public class CustomSpinner extends Spinner {
public CustomSpinner(Context context) {
super(context);
}
public void setSelectionByItemId(AdapterView<?> parent, long id){
for (int i = 0; i < parent.getCount(); i++) {
long itemIdAtPosition = parent.getItemIdAtPosition(i);
if (itemIdAtPosition == id) {
parent.setSelection(i);
break;
}
}
}
}
And this is the way I'm instantiating this class:
CustomSpinner spinner = (CustomSpinner) findViewById(R.id.sphofentries);
This give me an error at runtime.
All this is if R.id.sphofentries
is declared in my layout as an spinner.
But now, if I declare sphofentries
as a CustomSpinner
I get a runtime error just in the moment I set the Layout to the Activity:
setContentView(R.layout.settings);
Also I am pretty sure that the problem is that I need to declare sphofentries
as a CustomSpinner
because if I do this:
CustomSpinner spinner = new CustomSpinner(this);
spinner = (CustomSpinner) findViewById(R.id.sphofentries);
This goes without problem trough the first line but gives a runtime error in the second then the problem isn't creating a new CustomSpinner
but setting the sphofentries
in this CustomSpinner
(This with sphofentries
declared like a Spinner
not a CustomSpinner
).
Maybe I am doing something wrong in the layout, this is the way I am declaring sphofentries
as a CustomSpinner
:
<CustomSpinner
android:id="@+id/sphofentries"
android:layout_below="@+id/tvhofentries"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
/>