Implementing custom numberpicker into activity - android

I have this code in activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyNumberPicker np = new MyNumberPicker(this);
np.setOnScrollListener(new NumberPicker.OnScrollListener() {
#Override
public void onScrollStateChange(NumberPicker view, int scrollState) {
if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
np.setBottomFadingEdgeStrength(0.9f);
np.setBottomFadingEdgeStrength(0.9f);
} else if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE){
np.setBottomFadingEdgeStrength(1.0f);
np.setBottomFadingEdgeStrength(1.0f);
}
//also you can handle SCROLL_STATE_FLING if you want
}
});
}
}
And this code for my custom class:
public class MyNumberPicker extends NumberPicker {
private float bottomFadingEdgeStrength = 1.0f;
private float topFadingEdgeStrength = 1.0f;
public MyNumberPicker(Context context) {
super(context);
}
public MyNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyNumberPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected float getBottomFadingEdgeStrength() {
return bottomFadingEdgeStrength;
}
#Override
protected float getTopFadingEdgeStrength() {
return topFadingEdgeStrength;
}
void setTopFadingEdgeStrength(float strength){
topFadingEdgeStrength = strength;
}
void setBottomFadingEdgeStrength(float strength){
bottomFadingEdgeStrength = strength;
}
}
The thing is that I don't know how to add this number picker into activity. In other words, I can't get it to work in my program. So how should I change my code in activity to do this.
As far as I can tell, I can't use findViewById(R.id.numberpicker1). Please help.

In your layout, instead using adding a NumberPicker like you normally would:
<NumberPicker android:id="#+id/numberpicker1" ... />
You would use a tag that points to your custom class.
<your.path.to.MyNumberPicker android:id="#+id/numberpicker1" ... />
So, if you added this to your activity_main layout, you could initialize it using View.findViewById:
setContentView(R.layout.activity_main);
final MyNumberPicker np = (MyNumberPicker) findViewById(R.id.numberpicker1);

Related

Android Studio: Create Object in custom SwipeButton with attributes from XML

public class SwipeButton extends RelativeLayout {
private ImageView swipeButtonInner;
private float initialX;
private boolean active;
private TextView centerText;
private ViewGroup background;
private Drawable disabledDrawable;
private Drawable enabledDrawable;
private OnStateChangeListener onStateChangeListener;
private OnActiveListener onActiveListener;
private static final int ENABLED = 0;
private static final int DISABLED = 1;
private int collapsedWidth;
private int collapsedHeight;
private LinearLayout layer;
private boolean trailEnabled = false;
private boolean hasActivationState;
public SwipeButton(Context context) {
super(context);
init(context, null, -1, -1);
}
public SwipeButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, -1, -1);
}
public SwipeButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, -1);
}
#TargetApi(21)
public SwipeButton(Context context, AttributeSet attrs, int defStyleAttr, int
defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
public boolean isActive() {
return active;
}
public void setText(String text) {
centerText.setText(text);
}
public void setBackground(Drawable drawable) {
background.setBackground(drawable);
}
public void setSlidingButtonBackground(Drawable drawable) {
background.setBackground(drawable);
}
public void setDisabledDrawable(Drawable drawable) {
disabledDrawable = drawable;
if (!active) {
swipeButtonInner.setImageDrawable(drawable);
}
}
public void setButtonBackground(Drawable buttonBackground) {
if (buttonBackground != null) {
swipeButtonInner.setBackground(buttonBackground);
}
}
public void setEnabledDrawable(Drawable drawable) {
enabledDrawable = drawable;
if (active) {
swipeButtonInner.setImageDrawable(drawable);
}
}
public void setOnStateChangeListener(OnStateChangeListener
onStateChangeListener) {
this.onStateChangeListener = onStateChangeListener;
}
public void setOnActiveListener(OnActiveListener onActiveListener) {
this.onActiveListener = onActiveListener;
}
public void setInnerTextPadding(int left, int top, int right, int bottom) {
centerText.setPadding(left, top, right, bottom);
}
public void setSwipeButtonPadding(int left, int top, int right, int bottom) {
swipeButtonInner.setPadding(left, top, right, bottom);
}
public void setHasActivationState(boolean hasActivationState) {
this.hasActivationState = hasActivationState;
}
My XML:`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/AnswerRelativeLayout"
android:layout_height="70dp"
android:orientation="vertical"
tools:context="com.example.dynamicobj.FragmentMain">
<com.example.dynamicobj.SwipeButton
android:id="#+id/test_btn"
android:layout_width="match_parent"
android:layout_height="70dp"
app:button_background="#drawable/shape_button"
app:button_image_disabled="#drawable/ic_launcher_background"
app:button_image_height="60dp"
app:button_image_width="100dp"
app:has_activate_state="true"
app:initial_state="disabled"
app:inner_text="Termine buchen"
app:inner_text_background="#drawable/shape_rounded"
app:inner_text_bottom_padding="18dp"
app:inner_text_right_padding="200dp"
app:inner_text_color="#android:color/black"
app:inner_text_size="16sp"
app:inner_text_top_padding="18dp" />
</LinearLayout>`
F
ragmentMain:
public class FragmentMain extends Fragment {
Context context;
View rootView;
public FragmentMain() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
LinearLayout layout = (LinearLayout)
rootView.findViewById(R.id.AnswerRelativeLayout);
SwipeButton button = new SwipeButton(getContext());
layout.addView(button);
return rootView;
}
}
So I got this custom SwipeButton class from Git (com.ebanx.swipebtn.SwipeButton). Now I want to create an Object from SwipeButton with a layout looking like the one from the xml file. Is there any method, where I just can give the new button the prefinished layout without having to use all these Methods in the SwipeButton class? I am going to create the buttons dynamically later on, but all being the same layout. Help pls?
you forgot to add LayoutParams to your button
use below code before adding button into layout
button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
and set your LinearLayout height wrap_content not 70dp

How to create a a expandable view in android?

I want to expand the view on clicking the + button and this + sign changes to - when the view expanded.Again when i click the - button the view should be shrink.
Inside the view i have some TextView field.Please anyone suggest me.I am new to android.
This answer solves the question.
public class ExpandableTextView extends TextView implements OnClickListener
{
private static final int MAX_LINES = 5;
private int currentMaxLines = Integer.MAX_VALUE;
public ExpandableTextView(Context context)
{
super(context);
setOnClickListener(this);
}
public ExpandableTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setOnClickListener(this);
}
public ExpandableTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
setOnClickListener(this);
}
#Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)
{
/* If text longer than MAX_LINES set DrawableBottom - I'm using '...' icon */
post(new Runnable()
{
public void run()
{
if (getLineCount()>MAX_LINES)
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.icon_more_text);
else
setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
setMaxLines(MAX_LINES);
}
});
}
#Override
public void setMaxLines(int maxLines)
{
currentMaxLines = maxLines;
super.setMaxLines(maxLines);
}
/* Custom method because standard getMaxLines() requires API > 16 */
public int getMyMaxLines()
{
return currentMaxLines;
}
#Override
public void onClick(View v)
{
/* Toggle between expanded collapsed states */
if (getMyMaxLines() == Integer.MAX_VALUE)
setMaxLines(MAX_LINES);
else
setMaxLines(Integer.MAX_VALUE);
}
}
You can visible or gone particular layout on button click event at runtime like below code:
findViewById(R.id.yourButtonId).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mainView.setVisibility(View.GONE);
}
});

Cannot resolve method 'super()' error in android studio

I am getting the error: "Cannot resolve method 'super()'" in my code and I am not sure how to resolve this, do you have any clues?
The code is as follows:
public GeoView( double left, double top, double width )
{
super();
this.left = left;
this.top = top;
this.width = width;
this.transform = null;
this.backing_store = null;
this.sink = false;
this.last_size = new Rect(0, 0, 200, 200 );
this.do_tracking = false;
Drawable background = new Drawable() {
#Override
public void draw(Canvas canvas) {
}
#Override
public void setAlpha(int i) {
}
#Override
public void setColorFilter(ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return 0;
}
};
What is GeoView class? You extended it from another class?
If yes. Check that parent class have empty constructor, because you call it.
If it's your own class and it didn't extended from any other class. Then you don't need to call super().
View doesn't have empty constructor.
You should Have at least one of this constructor.
public GeoView(Context context) {
super(context);
}
public GeoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GeoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
If you want to create view by yourself, you need first constructor. Then you have to
GeoView geoView = new GeoView(YourActivity.this);
Or you can simply add your view to layout. Then You second will be called constructor. I think you should add all of them.
<com.example.yourapp.GeoView
android:layout_height="300dp"
android:layout_width="match_parent"/>

Setting custom ttf font in preference activity

i am trying to set a custom TTF font inside my PreferenceActivity.
The preference activity contains 2 ListPreferences, nothing else.
Inside my PreferenceActivity, i have this code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference conPref = findPreference(key);
// this works correctly, i'm able to get the correct text form tv.getText();
TextView tv = (TextView) conPref.getView(null, null).findViewById(android.R.id.title);
Typeface gilFontBook = Typeface.createFromAsset(getAssets(), "fonts/gilbook.ttf");
tv.setTypeface(gilFontBook); // doesnt change the typeface
}
But this doesn't work form me. The fontface remains the same before and after selecting an item from the ListPreference
As far as I know you've to extend the PreferenceActivity class to do that. This answer helped me:
https://stackoverflow.com/a/13193623/814353
I did it the bruteforce way:
public class FontPreference extends Preference {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public FontPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public FontPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FontPreference(Context context) {
super(context);
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
loopOverViewGroup(view);
}
private void loopOverViewGroup(View view){
if(view instanceof ViewGroup){
ViewGroup group = (ViewGroup)view;
for(int i = 0; i < ((ViewGroup)view).getChildCount(); i++){
View childView = ((ViewGroup)view).getChildAt(i);
if(childView instanceof ViewGroup){
loopOverViewGroup(childView);
}else{
setTypeFace(childView);
}
}
}
}
private void setTypeFace(View view){
if(view instanceof TextView){
((TextView)view).setTypeface(Typeface.createFromAsset(getContext().getAssets(), "YOURFONT.ttf"));
((TextView)view).setTextColor(getContext().getResources().getColor(Color.WHITE));
}
}
}

How do I draw a drawable with its exact size in my custom view?

SOLVED: Solution below as answer.
I have a custom view with a TransitionDrawable and when I draw it in the onDraw() method it scales automatically to fill the whole parent layout, even when it's set in the xml to wrap_content. The picture is in mdpi and hdpi and my testing device (samsung galaxy s) I think it's no more than hdpi.
package com.adyrsoft.pronunciationtrainer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private TransitionDrawable mDrawable;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
super(context);
init();
}
public RecordButton(Context context, AttributeSet attrib) {
super(context, attrib);
init();
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
Log.d(TAG, "Drawable intrinsic width and height are: " +
Integer.toString(mDrawable.getIntrinsicWidth()) + " " +
Integer.toString(mDrawable.getIntrinsicHeight()));
mDrawable.setBounds(0,0,mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
Log.d(TAG, "The bounds for the button are: "+mDrawable.getBounds().flattenToString());
super.setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
protected void onDraw (Canvas canvas) {
super.onDraw(canvas);
}
}
What am I doing wrong?
Thanks.
After hours trying to understand how I should use the drawables in a custom view in order to be displayed in its original size, I've figured out how to do it.
First a few things that I didn't know but are a must is:
The background drawable should be left to the parent class to be
drawn when using View as the parent. If not, the TransitionDrawable can't be seen fading between pictures.
Only if I am going to draw on the background drawable I should override onDraw() and do the drawing there.
And the last but not less important is that I should override onMeasure() to specify the size of the view. If I don't do it, it will fill all the free space in the parent layout, as it was happening to me.
I've passed the TransitionDrawable to the parent class with setBackgroundDrawable() and since I wasn't drawing in the background drawable, I've removed the onDraw() method. Also I've implemented onMeasure() with a quick and dirty solution specifying the size of the picture I am drawing.
This is the final result:
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private static final int DESIRED_WIDTH = 180;
private static final int DESIRED_HEIGHT = 66;
private TransitionDrawable mDrawable;
private Rect mViewRect;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
this(context, null, 0);
}
public RecordButton(Context context, AttributeSet attrib) {
this(context, attrib, 0);
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
#Override
protected void onMeasure(int m, int n) {
setMeasuredDimension(DESIRED_WIDTH, DESIRED_HEIGHT);
}
}

Categories

Resources