Android Widget Usage

Hy everyone, I am trying to use android widgets in my app, however I don’t know exactly how activity, context, ect. works. At the moment I have this code:

//imports
import android.app.Activity;
import android.content.Context;
import android.widget.NumberPicker;

Activity act;
NumberPicker numberPicker;

void setup() {
   fullScreen();
   frameRate(60);

   act = this.getActivity();

   numberPicker = new NumberPicker(act.getApplicationContext());
    numberPicker.setMaxValue(20);
    numberPicker.setMinValue(1);
    numberPicker.setX(200);
    numberPicker.setY(200);
    //numberPicker.setDisplayedValues(****);
}

void draw(){
}

I can compile and run the app in my phone, however it does not show the numberPicker, what do I miss?
And there is any good guide on how to use this widgets in processing android?

1 Like

@macarrony00===
numberPicker is a view; your code creates the object but never add it using addView: so you cannot see it; in the previous forum i have given snippets for doing that (for buttons, textView, editText etc).

Before my post I saw your reply here:
https://forum.processing.org/two/discussion/16539/how-to-manually-create-android-textfield-in-processing

It makes sense to need addView(numberPicker), however I need to have a frameLayout and use:
fl = (FrameLayout)act.findViewById( 0x1000 )
Most of the time I see the input like: “R.id.example” but for that I need the XML right? you use 0x1000 why?

@macarrony00===
fl is the frameLayout created by P5; 0x1000 was working when i have posted this code but now it does not work anymore because this id is generated randomly by the mainActivity: solution is to get fl with another way, that is:

fl = (FrameLayout)act.getWindow().getDecorView().getRootView();

Ok, now I can run the code:

Activity act;
NumberPicker numberPicker;
FrameLayout fl;

void setup() {
   fullScreen();
   frameRate(60);

   act = this.getActivity();

   numberPicker = new NumberPicker(act.getApplicationContext());
    numberPicker.setMaxValue(20);
    numberPicker.setMinValue(1);
    numberPicker.setX(200);
    numberPicker.setY(200);
    
   fl = (FrameLayout) act.getWindow().getDecorView().getRootView();
}

void draw(){
   fl.addView(numberPicker);
}

but I got this error:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

@macarrony00===
that is normal with android; in order to solve that you have to use a runnable:

runOnUiThread(new Runnable() {

    @ Override
    public void run() {

      //here you can update your uithread

    }
});

more details here:https://developer.android.com/reference/android/app/Activity#runOnUiThread(java.lang.Runnable)

Thank you, it’s working now :slight_smile: