How to call or use a View or Widget from another android class - android-darkmode

I have a little issue in android studio Java code !
Im using switch compact to change the background image from a light one to a dark one instead of NightMode. Every thing works fine in a class called "Category Activity" where the switch compact is there, but i want this to work in another class i mean whenever i click on switch compact the background Image change in all activity
Here is the code in "Category Activity" :
// ----------- DAY AND NIGHT MODE ----------------------//
switchCompat = findViewById(R.id.switchCompat);
back_images = new int[]{R.drawable.lightbg, R.drawable.darkbg};
switchCompat = findViewById(R.id.switchCompat);
screenView = findViewById(R.id.layoutcategory);
sharedPreferences = getSharedPreferences("dark_light", 0);
Boolean booleanValue = sharedPreferences.getBoolean("dark_light_mode", true);
if (booleanValue) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(true);
screenView.setBackgroundResource(R.drawable.lightbg);
switchCompat.setText(R.string.LightMode);
} else {
switchCompat.setChecked(false);
screenView.setBackgroundResource(R.drawable.darkbg);
switchCompat.setText(R.string.NightMode);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(true);
screenView.setBackgroundResource(R.drawable.lightbg);
switchCompat.setText(R.string.LightMode);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode", true);
editor.commit();
} else {
screenView.setBackgroundResource(R.drawable.darkbg);
switchCompat.setText(R.string.NightMode);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode", false);
editor.commit();
}
}
});

Related

How hide items when print current page?

I create my web project by Vaadin 7.3.6
When I want to print current page I use this:
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
private ClickListener printListener;
printListener = new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
JavaScript.getCurrent().execute("print();");
}
};
As result it's print current page.
The page content from text and two buttons (Print, OK) on the bottom of page. Nice.
But I want to print only text. Without this 2 buttons.
I want to hide buttons ONLY when printing current page.
When return to page I want to see again this two buttons.
How I can do this?
P.S. I try this:
final Button okButton = new Button(MessageService.getMessage("ok"));
final Button printButton = new Button(MessageService.getMessage("print"));
printButton.setStyleName("small-top-margin");
final JavaScript js = JavaScript.getCurrent();
final UI ui = UI.getCurrent();
printButton.addClickListener(event -> {
logger.debug("click_print");
Thread thread = new Thread(() -> {
ui.access(() -> {
logger.debug("hide_all_buttons");
printButton.setVisible(false);
okButton.setVisible(false);
js.execute("print();");
});
try {
logger.debug("wating_n_seconds");
Thread.sleep(3000);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
ui.access(() -> {
logger.debug("show_all_buttons");
printButton.setVisible(true);
okButton.setVisible(true);
});
});
thread.start();
}); // click listener
First click on printButton - nothing happened
Second click on printButton - print all buttons. It's not correct.
You can hide the button easily with button.setVisible(false). The true trick is to get the button back. One one is to do this in thread and have sufficient delay before switching the button back visible. Here is an example (Java 8 syntax to make it more compact) This works both with Vaadin 7 & 8.
final Button print = new Button("Print");
final UI ui = this; // or UI.getCurrent() or getUI() depending where you are
final JavaScript js = JavaScript.getCurrent();
print.addClickListener(event -> {
Thread t = new Thread(() -> {
ui.access(() -> {
print.setVisible(false);
js.execute("print();");
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ui.access(() -> print.setVisible(true));
});
t.start();
});
layout.addComponent(print);
Alternative approach is to use theming, I.e.
Button print = new Button("Print");
print.addStyleName("no-print");
And the following into your mytheme.scss file, before #mixin mytheme
#media print {
.no-print {
display:none;
}
}

Can I bind the return to a condition?

I have the following problem:
My method opens a JDialog with a bunch of buttons (only one in example code). I want to click a button and thereby choose an ImageIcon for my method to return. But the Method does not wait for me to click a button. It opens the window and then returns an empty ImageIcon.
public class Kartenauswahl {
ImageIcon bandit;
public ImageIcon auswahlfenster() {
int bwidth = new Integer(150);
int bheight = new Integer(225);
bandit = new ImageIcon("cover/Bandit.jpe");
bandit.setImage(bandit.getImage().getScaledInstance(bwidth,bheight,Image.SCALE_DEFAULT));
final JDialog kartenwahl = new JDialog();
kartenwahl.setTitle("Kartenwahl");
kartenwahl.setSize(1500,1000);
kartenwahl.setVisible(true);
kartenwahl.setLayout(new FlowLayout());
ImageIcon returnicon= new ImageIcon();
final JButton b1 = new JButton(); //just to get the Icon out of the void loop
JButton B1 = new JButton(bandit); //this is going to be the button I want to click to choose the ImageIcon which is returned
B1.setContentAreaFilled(false);
B1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
b1.setIcon(bandit);
kartenwahl.dispose();
}
});
kartenwahl.add(B1);
returnicon = (ImageIcon) b1.getIcon();
return returnicon;
}
}
Question: can I bind the return statement to a condition? Like "only return after I clicked that Button B1"?
Hi sorry for the long wait. I have written an custom JDialog that should work for you.
public class CustomDialog extends JDialog {
JButton[] buttons;
ImageIcon selectedImageIcon;
public CustomDialog() {
setSize(500, 500);
setLayout(new GridLayout(4, 6));
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
selectedImageIcon = ((ImageIcon) ((JButton) e.getSource()).getIcon());
dispose();
}
};
buttons = new JButton[24];
for(int i = 0; i < 24; i++) {
buttons[i] = new JButton(new ImageIcon("path_to_your_image_file"));
buttons[i].addActionListener(actionListener);
add(buttons[i]);
}
setVisible(true);
}
public ImageIcon getSelectedImageIcon() {
return selectedImageIcon;
}
}
The initial size is not that important the GridLayout is. you mentioned that you would need 24 buttons so I created an grid with 4 rows and 6 columns.
Then I create the buttons in a loop and adding the same Listener to set the selection icon with the icon of the pressed button. Afterwards I dispose the screen triggering an windowClosed event.
You could simply create this Dialog from your main class and wait for the response like so:
public class main {
public static void main(String[] args) {
CustomDialog customDialog = new CustomDialog();
customDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
ImageIcon icon = customDialog.getSelectedImageIcon();
//do something with your icon
}
});
}
}
Don't forget to mark this answer as correct if it fixes your problem.
Have a good one!

Vaadin Grid ItemClickListener fails to register clicks on column with ImageRenderer

I have the following code which is supposed to show a clickable icon which opens a popup dialog reading out a lengthy note.
this.capacityCommentColumn = this.facilityGrid.addColumn(
p -> {
if (Strings.isNullOrEmpty(p.getCapacityComment())) {
return null;
} else {
return new ThemeResource("img/note.svg");
}
},
new ImageRenderer<>())
.setWidth(80)
.setCaption("Note");
this.facilityGrid.addItemClickListener(new ItemClickListener<MapQueryService.RowResult>() {
#Override
public void itemClick(Grid.ItemClick<MapQueryService.RowResult> event) {
if (event.getColumn() == capacityCommentColumn && !Strings.isNullOrEmpty(event.getItem().getCapacityComment())) {
final NoteWindow noteWindow = new NoteWindow();
noteWindow.txtDescription.setValue("test");
noteWindow.show();
}
}
});
The problem is the code does not respond to clicks on the actual image, only on the outside. You can see this below. Any idea if its possible to make the image clickable?
You need to add a click listener to the Renderer as well. For example:
Grid<Integer> grid = new Grid();
private void addIconColumn() {
ImageRenderer<Integer> renderer = new ImageRenderer<>();
renderer.addClickListener(e -> iconClicked(e.getItem())); // allow clicks on the image
Grid.Column<Integer, ThemeResource> iconColumn = grid.addColumn(i -> new ThemeResource("img/icon.svg"), renderer)
.setCaption("Icon");
grid.addItemClickListener(e -> { // allow clicks on the cell
if (iconColumn.equals(e.getColumn())) {
iconClicked(e.getItem());
}
});
}
private void iconClicked(Integer i) {
... your UI logic here ...
}
You can see a working example here: https://github.com/alejandro-du/community-answers/tree/master/click-image-in-grid

Change "Active" icon on selected NavigationPage when using TabbedPage

I'm very, very new to Xamarin.Forms. My task, if it is possible, and I'm not sure if it is, is to change our icon from the default blue when it is active.
I was given icons that are orange and they would like to display those or at least the color instead of the default blue. Again, I'm not sure if this is possible.
This is the code I'm using for the tabbed page.
public class LandingPage : TabbedPage
{
public LandingPage ()
{
NavigationPage homepage = new NavigationPage (new CarouselPage {
Title = "Title",
Children = {
//code removed
}
});
NavigationPage eventspage = new NavigationPage (new ContentPage {
Title = "Calendar Event List",
Content = new EventList ()
});
NavigationPage morepage = new NavigationPage (new MorePage ());
homepage.BarBackgroundColor = Device.OnPlatform (Color.FromHex (DependencyService.Get<IContentStrings>().BarBackgroundColor), Color.Transparent, Color.Transparent);
homepage.BarTextColor = Color.FromHex(DependencyService.Get<IContentStrings>().BarTextColor);
homepage.Title = DependencyService.Get<IContentStrings>().HomeTitle;
homepage.Icon = DependencyService.Get<IContentStrings>().HomeImage;
eventspage.BarBackgroundColor = Device.OnPlatform (Color.FromHex (DependencyService.Get<IContentStrings>().BarBackgroundColor), Color.Transparent, Color.Transparent);
eventspage.BarTextColor = Color.FromHex(DependencyService.Get<IContentStrings>().BarTextColor);
eventspage.Title = DependencyService.Get<IContentStrings>().EventTitle;
eventspage.Icon = DependencyService.Get<IContentStrings>().EventImage;
morepage.BarBackgroundColor = Device.OnPlatform (Color.FromHex (DependencyService.Get<IContentStrings>().BarBackgroundColor), Color.Transparent, Color.Transparent);
morepage.BarTextColor = Color.FromHex(DependencyService.Get<IContentStrings>().BarTextColor);
morepage.Title = DependencyService.Get<IContentStrings>().MoreTitle;
morepage.Icon = DependencyService.Get<IContentStrings>().MoreImage;
Children.Add (homepage);
Children.Add (eventspage);
Children.Add (morepage);
}
}
I'm not sure if I'm able to use a custom renderer or anything. I do not know if I have any options and any guidance is greatly appreciated!
You can set the active tab icon color with a simple custom iOS renderer like this:
[assembly: ExportRenderer(typeof(TabbedPage), typeof(MyTabbedPageRenderer))]
namespace MyApp.iOS.Renderers
{
public class MyTabbedPageRenderer : TabbedRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
TabBar.TintColor = UIColor.Orange;
}
}
}
I found was finally able to find the answer after searching the internet a few hours and then coming back to the app on a different day. To change the default from the blue, I changed the UITabbar tint color in the AppDelegate.
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
UIApplication.SharedApplication.SetStatusBarStyle (UIStatusBarStyle.LightContent, false);
global::Xamarin.Forms.Forms.Init ();
LoadApplication (new App ());
//this changes the default iOS tintcolor for the icon when it's activated
UITabBar.Appearance.TintColor = UIColor.FromRGB(223, 112, 13);
return base.FinishedLaunching (app, options);
}

BlackBerry - Simulate a KeyPress event

I have a BlackBerry application that needs to take pictures from the camera and send them to a server. In order to do this i invoke the native camera application and listen to the filesystem. Once an image is captured and saved as a new jpeg file i get notified, resume foreground control and go about my business. The problem starts occurring after the first time this cycle is completed because now when i decide to call the camera application again it is already opened, and now the user is seeing a thumbnail of the last picture that was taken and several buttons allowing him to manipulate/manage it. naturally what i want the user to see is a preview of what the camera is "seeing" before he snaps another photo as he did before.
I have thought of various ways to solve this including killing the camera app each time (I understand this cannot be done programatically?), sending CameraArguments when invoking the app (which appears to be useless), and now i was thinking a solution could be as simple generating a "Back" key event before switching back to my app which would theoretically dismiss the annoying edit screen. Could this really be done? and if not is there any other possible solution you may think of?
A kind of hack...
start Camera App
in TimerTask check if Camera App started and if it need to be closed (some flag)
if yes, invoke it(so it will became active) and push ESC keypress event injection to close it
Take a look at this:
class Scr extends MainScreen {
boolean killCameraApp = false;
final String mCameraModuleName = "net_rim_bb_camera";
final CameraArguments args = new CameraArguments();
public Scr() {
super();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (isCameraRunning() && killCameraApp) {
getApplication().invokeAndWait(callCamera);
getApplication().invokeAndWait(killCamera);
}
}
}, 0, 100);
}
Runnable callCamera = new Runnable() {
public void run() {
callCamera();
}
};
Runnable killCamera = new Runnable() {
public void run() {
injectKey(Characters.ESCAPE);
killCameraApp = false;
}
};
private boolean isCameraRunning() {
boolean result = false;
ApplicationManager appMan =
ApplicationManager.getApplicationManager();
ApplicationDescriptor[] appDes = appMan.getVisibleApplications();
for (int i = 0; i < appDes.length; i++) {
result = mCameraModuleName.equalsIgnoreCase(appDes[i]
.getModuleName());
if (result)
break;
}
return result;
}
private void callCamera() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
private void injectKey(char key) {
KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, key, 0);
inject.post();
}
protected void makeMenu(Menu menu, int instance) {
menu.add(new MenuItem("start camera", 0, 0) {
public void run() {
callCamera();
killCameraApp = false;
}
});
menu.add(new MenuItem("kill app", 0, 0) {
public void run() {
killCameraApp = true;
}
});
super.makeMenu(menu, instance);
}
}
EDIT: Don't forget to set permissions for device release:
Options => Advanced Options => Applications => [Your Application] =>Edit Default permissions =>Interactions =>key stroke Injection

Resources