How to resize layout containers when the parent window resizes? - gtk3

I am developing a music player application in Vala 0.14. The main toolbar of this application contains nested Box Layouts and all of them have the hexpand property set to true.
While packing the widgets/layouts I made sure that the expand and fill arguments were true, however the toolbar fails to resize when the size of parent window changes.
Here are the screenshots.
[NORMAL]
[RESIZE -- SIZE INCREASED]
[RESIZE -- SIZE DECREASED]
Is it enough to set the hexpand property to true or do I need to make some adjustments to the box layouts when the parent window's size_allocate signal is emitted ?
CODE:
using Gtk;
namespace Conjure.Widget
{
public class MainToolBar : Object
{
/* Declare reference variables */
private Toolbar tlbMain;
private ToolItem tiMain;
public Scale sclProgress;
private Label lblSongName;
private Label lblArtistName;
private Label lblAlbumName;
private Box hboxMain;
private Box vboxControls;
private Box hboxControls;
private Box hboxButtons;
private Box hboxMetaData;
private Box vboxMetaData;
private Box vboxPreferences;
private Box hboxPreferences;
private Image imgArt;
private Image icnPrevious;
public Image icnPlay;
public Image icnPause;
private Image icnNext;
private Image icnRepeat;
private Image icnVolume;
private Image icnPhone;
private Image icnSuperMenu;
private Image icnEqualizer;
public Button btnPrevious;
public Button btnTogglePlay;
public Button btnNext;
public Button btnVolume;
public Button btnSuperMenu;
public Button btnEqualizer;
private ToggleButton btnPhone;
private ToggleButton btnRepeat;
private Separator sep1;
private Separator sep2;
construct
{
/* Create the parent box */
hboxMain = new Box(Orientation.HORIZONTAL, 0);
hboxMain.hexpand = true;
hboxMain.homogeneous = true; //
/* Create boxes to hold meta data */
hboxMetaData = new Box(Orientation.HORIZONTAL, 5);
vboxMetaData = new Box(Orientation.VERTICAL, 0);
vboxMetaData.homogeneous = true;
hboxMetaData.hexpand = true;
vboxMetaData.hexpand = true;
/* Create boxes for control elements */
vboxControls = new Box(Orientation.VERTICAL, 0);
hboxControls = new Box(Orientation.HORIZONTAL, 0);
hboxButtons = new Box(Orientation.HORIZONTAL, 0);
vboxControls.homogeneous = true;
vboxControls.hexpand = true;
hboxButtons.homogeneous = false;
hboxButtons.hexpand = true;
hboxButtons.halign = Align.CENTER;
hboxControls.hexpand = true;
/* Create boxes for preference control */
vboxPreferences = new Box(Orientation.VERTICAL, 0);
hboxPreferences = new Box(Orientation.HORIZONTAL, 0);
vboxPreferences.hexpand = true;
hboxPreferences.hexpand = true;
/* Create and load image mockup */
imgArt = new Image();
//imgArt.set_from_file("/home/utsav/jmrfs.png");
imgArt.halign = Align.START;
/* Make labels for meta data */
lblSongName = new Label(null);
lblArtistName = new Label(null);
lblAlbumName = new Label(null);
lblSongName.set_markup_with_mnemonic("<b>Down</b>");
lblArtistName.set_markup_with_mnemonic("Jay Sean ft. Lil' Wayne");
lblAlbumName.set_markup_with_mnemonic("All or Nothing");
lblSongName.halign = Align.START;
lblArtistName.halign = Align.START;
lblAlbumName.halign = Align.START;
lblSongName.hexpand = true;
lblAlbumName.hexpand = true;
lblArtistName.hexpand = true;
/* Create audio progress bar */
sclProgress = new Scale(Gtk.Orientation.HORIZONTAL, new Adjustment(0.0, 0.0, 10.0, 0.1, 1.0, 1.0));
sclProgress.draw_value = false;
sclProgress.width_request = 300;
// Stylize control
/*StyleContext style_context = sclProgress.get_style_context();
CssProvider css_provider = new CssProvider();
try
{
css_provider.load_from_path(Conjure.Utility.path_to_assets () + "/css/style.css");
}
catch(Error e)
{
stderr.puts("Unable to load specified style sheet.");
}
style_context.add_provider(css_provider, STYLE_PROVIDER_PRIORITY_THEME);*/
/* Create toolbar buttons */
btnPrevious = new Button();
btnTogglePlay = new Button();
btnNext = new Button();
btnVolume = new Button();
btnSuperMenu = new Button();
btnEqualizer = new Button();
btnRepeat = new ToggleButton();
btnPhone = new ToggleButton();
btnPrevious.hexpand = false;
icnPrevious = new Image();
icnPause = new Image();
icnPlay = new Image();
icnNext = new Image();
icnPhone = new Image();
icnRepeat = new Image();
icnVolume = new Image();
icnSuperMenu = new Image();
icnEqualizer = new Image();
/*icnPrevious.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-skip-backward.png");
icnPlay.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-playback-start.png");
icnPause.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-playback-pause.png");
icnNext.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-skip-forward.png");
icnPhone.set_from_file(Conjure.Utility.path_to_assets () + "/icons/phone.png");
icnRepeat.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-playlist-repeat.png");
icnVolume.set_from_file(Conjure.Utility.path_to_assets () + "/icons/audio-volume-high.png");
icnSuperMenu.set_from_file(Conjure.Utility.path_to_assets () + "/icons/document-properties.png");
icnEqualizer.set_from_file(Conjure.Utility.path_to_assets () + "/icons/media-graphic-equalizer.png");
btnPrevious.image = icnPrevious;
btnNext.image = icnNext;
btnTogglePlay.image = icnPlay;
btnPhone.image = icnPhone;
btnRepeat.image = icnRepeat;
btnVolume.image = icnVolume;
btnSuperMenu.image = icnSuperMenu;
btnEqualizer.image = icnEqualizer;*/
sep1 = new Separator(Orientation.VERTICAL);
sep2 = new Separator(Orientation.VERTICAL);
/* Start packing widgets */
// Pack Meta Data Box
vboxMetaData.pack_start(lblSongName, true, true, 0);
vboxMetaData.pack_start(lblAlbumName, true, true, 0);
vboxMetaData.pack_start(lblArtistName, true, true, 0);
hboxMetaData.pack_start(imgArt, false, true, 0);
hboxMetaData.pack_start(vboxMetaData, true, true, 0);
// Pack controls box
vboxControls.pack_start(sclProgress, true, true, 0);
hboxButtons.pack_start(btnPrevious, false, false, 0);
hboxButtons.pack_start(btnTogglePlay, false, false, 0);
hboxButtons.pack_start(btnNext, false, false, 0);
hboxButtons.pack_start(sep1, false, false, 0);
hboxButtons.pack_start(btnRepeat, false, false, 0);
hboxButtons.pack_start(btnVolume, false, false, 0);
hboxButtons.pack_start(sep2, false, false, 0);
hboxButtons.pack_start(btnPhone, false, false, 0);
vboxControls.pack_start(hboxButtons, true, true, 0);
// Pack preference box
hboxPreferences.pack_end(btnSuperMenu, false, false, 0);
hboxPreferences.pack_end(btnEqualizer, false, false, 0);
vboxPreferences.pack_end(hboxPreferences, false, false, 0);
vboxPreferences.halign = Align.END;
// Pack main box
hboxMain.pack_start(hboxMetaData, true, true, 0);
hboxMain.pack_start(vboxControls, true, true, 0);
hboxMain.pack_start(vboxPreferences, true, true, 0);
/* Create ToolItem */
tiMain = new ToolItem();
tiMain.add(hboxMain);
tiMain.hexpand = true;
/* Create Toolbar */
tlbMain = new Toolbar();
tlbMain.add(tiMain);
tlbMain.hexpand = true;
tlbMain.vexpand = false;
}
public void resize_main_layout()
{
}
public Gtk.Widget toolbar
{
get
{
return tlbMain;
}
}
}
}
[Main Module]
using Gtk;
using Conjure.Widget;
namespace Conjure.App
{
public class MainWindow : Window
{
private Box vboxMain;
private Box hboxPlaylists;
private MainToolBar maintoolbar;
/*private Conjure.Library.MusicPlayer player;
private SyncThread t;
public Cancellable c;
private unowned Thread<void*> t_a;
// dummy variable
bool track_selected;*/
construct
{
this.title = "Conjure";
this.set_default_size(905, 600);
this.window_position = WindowPosition.CENTER;
//t = null;
//c = null;
//track_selected = true;
vboxMain = new Box(Orientation.VERTICAL, 0);
hboxPlaylists = new Box(Orientation.HORIZONTAL, 0);
maintoolbar = new MainToolBar();
//player = Conjure.Library.MusicPlayer.get();
vboxMain.homogeneous = false;
vboxMain.pack_start(maintoolbar.toolbar, false, true, 0);
//maintoolbar.btnTogglePlay.clicked.connect(toggle_play_clicked);
maintoolbar.sclProgress.set_state (Gtk.StateType.INSENSITIVE);
/*player.state_changed.connect(() =>
{
if(player.get_state() == Conjure.Library.States.READY)
{
track_selected = true;
update_metaphors ();
}
});*/
/*maintoolbar.sclProgress.change_value.connect((s, d) =>
{
stderr.printf("Moved\n");
player.toggle_play ();
player.seek_player((int64) d);
player.toggle_play ();
});
this.size_allocate.connect((allocation) =>
{
stderr.printf("Resized\n");
maintoolbar.resize_main_layout ();
vboxMain.resize_children ();
});*/
vboxMain.hexpand = true;
add(vboxMain);
}
/*void toggle_play_clicked(Gtk.Widget w)
{
w.set_sensitive (false);
if (new_track_selected () && player.get_state() != Conjure.Library.States.PLAYING)
{
stderr.puts("A\n");
kill_thread ();
player.set_track("/home/utsav/abc.mp3");
player.toggle_play ();
make_and_run_thread ();
}
else if (player.get_state() == Conjure.Library.States.PLAYING)
{
stderr.puts("B\n");
kill_thread ();
player.toggle_play ();
}
else if (!(new_track_selected ()) && player.get_state() == Conjure.Library.States.PAUSED)
{
stderr.puts("C\n");
player.toggle_play();
make_and_run_thread ();
}
update_metaphors ();
w.set_sensitive (true);
}*/
/*bool new_track_selected()
{
// method stub
bool p;
p = track_selected;
track_selected = false;
return p;
}*/
/*void kill_thread ()
{
try
{
if(c!=null)
{
c.cancel ();
t_a.join();
}
}
catch(ThreadError err)
{
stderr.printf ("Error: %s", err.message);
}
}
void make_and_run_thread()
{
try
{
c = new Cancellable();
t = new SyncThread(maintoolbar.sclProgress, player.audio_player (), c);
t_a = Thread.create<void*> (t.thread_func, true);
}
catch(ThreadError err)
{
stderr.printf ("Error: %s", err.message);
}
}*/
/*void update_metaphors()
{
if(player.get_state()== Conjure.Library.States.PLAYING)
{
maintoolbar.btnTogglePlay.image = maintoolbar.icnPause;
}
else
{
maintoolbar.btnTogglePlay.image = maintoolbar.icnPlay;
}
}*/
}
}

Without seeing the code it's hard to tell for sure, but my guess is that it does expand. Assuming you have a horizontal box with three children (one for each section) you probably want to set only the middle child to expand. Right now, that third child is also expanding and allocating whitespace.
My advice is to try to create your UI in Glade first. Even if you don't want to use Glade for the final product, it makes it easy to see what different configurations do and will make diagnosing issues like this much easier.

Related

how to stop tiles from spawning after a certain number in unity3d

I have a script that spawns endless tiles (3D) and i want it to stop at after a certain number (e.g. 100) and at the end of the last tile (the 100th) i want to spawn an other prefab like a portal.
I have no clue how to do that.
Any answer i have found on google couldnt help.
Any help is much appreciated.
void Start()
{
nextTileLocation = startPoint;
nextTileRotation = Quaternion.identity;
for (int i = 0; i < initSpawnNum; ++i)
{
SpawnNextTile (i >= initNoObstacles);
}
}
public void SpawnNextTile(bool spawnObstacles = true)
{
var newTile = Instantiate (tile, nextTileLocation, nextTileRotation);
var nextTile = newTile.Find ("Next Spawn Point");
nextTileLocation = nextTile.position;
nextTileRotation = nextTile.rotation;
if (!spawnObstacles)
return;
var obstacleSpawnPoints = new List<GameObject> ();
foreach (Transform child in newTile) {
if (child.CompareTag ("ObstacleSpawn")) {
obstacleSpawnPoints.Add (child.gameObject);
}
}
if (obstacleSpawnPoints.Count > 0) {
var spawnPoint = obstacleSpawnPoints [Random.Range (0, obstacleSpawnPoints.Count)];
var spawnPos = spawnPoint.transform.position;
var newObstacle = Instantiate (obstacle, spawnPos, Quaternion.identity);
newObstacle.SetParent (spawnPoint.transform);
}
}
You could do something like pass in a bool to tell the function to spawn a portal.
void Start()
{
nextTileLocation = startPoint;
nextTileRotation = Quaternion.identity;
for (int i = 0; i < initSpawnNum; ++i)
{
// Pass in true for the last tile
SpawnNextTile (i >= initNoObstacles, i == initSpawnNum - 1);
}
}
public void SpawnNextTile(bool spawnObstacles = true, bool shouldSpawnPortal = false)
{
//
}
Edit to show adding the tiles to a list:
class YourScript : MonoBehaviour
{
private List<GameObject> tiles = new List<GameObject>();
private void SpawnNextTile(bool spawnObstacles = true, bool shouldSpawnPortal = false)
{
var newTile = Instantiate (tile, nextTileLocation, nextTileRotation);
tiles.Add(newTile);
// The rest of your code
}
}

Start Android Wear Watchface from Activity

I am wondering if it's possible to start the Watchface Service from an activity?
I tried to start the service in the onCreate method of my activity but it does not show the Watchface:
Intent serviceIntent = new Intent(this, CustomWatchFaceService);
startService(serviceIntent);
update
Here is the code for the WatchfaceService
public class CustomWatchFaceService extends CanvasWatchFaceService {
private static final String TAG = "DigitalWatchFaceService";
private static final Typeface BOLD_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
private static final Typeface NORMAL_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
private static final long NORMAL_UPDATE_RATE_MS = 500;
private static final long MUTE_UPDATE_RATE_MS = TimeUnit.MINUTES.toMillis(1);
#Override
public Engine onCreateEngine() {
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine {
static final String COLON_STRING = ":";
static final int MUTE_ALPHA = 100;
static final int NORMAL_ALPHA = 255;
static final int MSG_UPDATE_TIME = 0;
long mInteractiveUpdateRateMs = NORMAL_UPDATE_RATE_MS;
final Handler mUpdateTimeHandler = new Handler() {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_UPDATE_TIME:
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "updating time");
}
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs =
mInteractiveUpdateRateMs - (timeMs % mInteractiveUpdateRateMs);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
break;
}
}
};
Paint mBackgroundPaint;
Bitmap mBackgroundBitmap;
Bitmap wifiIconOn;
Bitmap wifiIconOff;
Paint mDatePaint;
Paint mNotificationPaint;
Paint mNotificationMax;
Paint mNotificationHigh;
Paint mHourPaint;
Paint mMinutePaint;
Paint mSecondPaint;
Paint mAmPmPaint;
Paint mColonPaint;
float mColonWidth;
boolean mMute;
Calendar mCalendar;
Date mDate;
SimpleDateFormat mDayOfWeekFormat;
java.text.DateFormat mDateFormat;
boolean mShouldDrawColons;
float mXOffset;
float mYOffset;
float mLineHeight;
int mInteractiveBackgroundColor =
R.color.interactive_bg;
int mInteractiveNotificationMax =
R.color.notification_max;
int mInteractiveNotificationHigh =
R.color.notification_high;
int mInteractiveNotificationColor =
R.color.notification;
int mInteractiveHourDigitsColor =
R.color.interactive_time;
int mInteractiveMinuteDigitsColor =
R.color.interactive_time;
int mInteractiveSecondDigitsColor =
R.color.interactive_time;
boolean mLowBitAmbient;
#Override
public void onCreate(SurfaceHolder holder) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onCreate");
}
super.onCreate(holder);
Locale locale = new Locale("de");
Locale.setDefault(locale);
Configuration config = getResources().getConfiguration();
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
setWatchFaceStyle(new WatchFaceStyle.Builder(CustomWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
Resources resources = CustomWatchFaceService.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mLineHeight = resources.getDimension(R.dimen.digital_line_height);
setInteractiveColors();
// Not sure why the text color needs to be set here again ... it should be set in setDefaultColors()!
mDatePaint.setColor(getColor(R.color.digital_date));
mNotificationPaint.setColor(getColor(R.color.notification));
mNotificationMax.setColor(getColor(R.color.notification_max));
mNotificationHigh.setColor(getColor(R.color.notification_high));
mHourPaint.setColor(getColor(R.color.interactive_time));
mMinutePaint.setColor(getColor(R.color.interactive_time));
mSecondPaint.setColor(getColor(R.color.interactive_time));
mColonPaint.setColor(getColor(R.color.interactive_time));
//Images should be loaded here so they can be called during the Draw Method
wifiIconOn = BitmapFactory.decodeResource(CustomWatchFaceService.this.getResources(), R.drawable.wifi_on_small);
wifiIconOff = BitmapFactory.decodeResource(CustomWatchFaceService.this.getResources(), R.drawable.wifi_off_small);
mBackgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.customcart_logo_240_alpha);
mCalendar = Calendar.getInstance();
mDate = new Date();
initFormats();
}
public void setInteractiveColors() {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(mInteractiveBackgroundColor));
mNotificationPaint = createTextPaint(mInteractiveNotificationColor);
mNotificationMax = createTextPaint(mInteractiveNotificationMax);
mNotificationHigh = createTextPaint(mInteractiveNotificationHigh);
mDatePaint = createTextPaint(R.color.digital_date);
mHourPaint = createTextPaint(mInteractiveHourDigitsColor, BOLD_TYPEFACE);
mMinutePaint = createTextPaint(mInteractiveMinuteDigitsColor);
mSecondPaint = createTextPaint(mInteractiveSecondDigitsColor);
mColonPaint = createTextPaint(R.color.digital_colons);
}
#Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
private Paint createTextPaint(int defaultInteractiveColor) {
return createTextPaint(defaultInteractiveColor, NORMAL_TYPEFACE);
}
private Paint createTextPaint(int defaultInteractiveColor, Typeface typeface) {
Paint paint = new Paint();
paint.setColor(defaultInteractiveColor);
paint.setTypeface(typeface);
paint.setAntiAlias(true);
return paint;
}
#Override
public void onVisibilityChanged(boolean visible) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onVisibilityChanged: " + visible);
}
super.onVisibilityChanged(visible);
updateTimer();
}
private void initFormats() {
mDayOfWeekFormat = new SimpleDateFormat("EEEE", Locale.getDefault());
mDayOfWeekFormat.setCalendar(mCalendar);
mDateFormat = DateFormat.getDateFormat(CustomWatchFaceService.this);
mDateFormat.setCalendar(mCalendar);
}
#Override
public void onApplyWindowInsets(WindowInsets insets) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onApplyWindowInsets: " + (insets.isRound() ? "round" : "square"));
}
super.onApplyWindowInsets(insets);
// Load resources that have alternate values for round watches.
Resources resources = CustomWatchFaceService.this.getResources();
boolean isRound = insets.isRound();
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
float textSize = resources.getDimension(isRound
? R.dimen.digital_text_size_round : R.dimen.digital_text_size);
float notificationTextSize = resources.getDimension(isRound
? R.dimen.notification_text_size : R.dimen.notification_text_size);
mDatePaint.setTextSize(resources.getDimension(R.dimen.digital_date_text_size));
mHourPaint.setTextSize(textSize);
mMinutePaint.setTextSize(textSize);
mSecondPaint.setTextSize(textSize);
mColonPaint.setTextSize(textSize);
mNotificationPaint.setTextSize(notificationTextSize);
mColonWidth = mColonPaint.measureText(COLON_STRING);
}
#Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
boolean burnInProtection = properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false);
mHourPaint.setTypeface(burnInProtection ? NORMAL_TYPEFACE : BOLD_TYPEFACE);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onPropertiesChanged: burn-in protection = " + burnInProtection
+ ", low-bit ambient = " + mLowBitAmbient);
}
}
#Override
public void onTimeTick() {
super.onTimeTick();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onTimeTick: ambient = " + isInAmbientMode());
}
invalidate();
}
#Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (!isInAmbientMode()) {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(R.color.interactive_bg));
mDatePaint.setColor(getColor(R.color.digital_date));
mHourPaint.setColor(getColor(R.color.interactive_time));
mMinutePaint.setColor(getColor(R.color.interactive_time));
mSecondPaint.setColor(getColor(R.color.interactive_time));
mColonPaint.setColor(getColor(R.color.interactive_time));
}
else {
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(getColor(R.color.ambient_bg));
mDatePaint.setColor(getColor(R.color.digital_date));
mHourPaint.setColor(getColor(R.color.ambient_time));
mMinutePaint.setColor(getColor(R.color.ambient_time));
mSecondPaint.setColor(getColor(R.color.ambient_time));
mColonPaint.setColor(getColor(R.color.ambient_time));
}
//Log.d("XXX", "onAmbientModeChanged: " + inAmbientMode);
if (mLowBitAmbient) {
boolean antiAlias = !inAmbientMode;
mDatePaint.setAntiAlias(antiAlias);
mHourPaint.setAntiAlias(antiAlias);
mMinutePaint.setAntiAlias(antiAlias);
mSecondPaint.setAntiAlias(antiAlias);
mAmPmPaint.setAntiAlias(antiAlias);
mColonPaint.setAntiAlias(antiAlias);
}
invalidate();
// Whether the timer should be running depends on whether we're in ambient mode (as well
// as whether we're visible), so we may need to start or stop the timer.
updateTimer();
}
#Override
public void onInterruptionFilterChanged(int interruptionFilter) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "onInterruptionFilterChanged: " + interruptionFilter);
}
super.onInterruptionFilterChanged(interruptionFilter);
boolean inMuteMode = interruptionFilter == WatchFaceService.INTERRUPTION_FILTER_NONE;
// We only need to update once a minute in mute mode.
setInteractiveUpdateRateMs(inMuteMode ? MUTE_UPDATE_RATE_MS : NORMAL_UPDATE_RATE_MS);
if (mMute != inMuteMode) {
mMute = inMuteMode;
int alpha = inMuteMode ? MUTE_ALPHA : NORMAL_ALPHA;
mDatePaint.setAlpha(alpha);
mHourPaint.setAlpha(alpha);
mMinutePaint.setAlpha(alpha);
mColonPaint.setAlpha(alpha);
mAmPmPaint.setAlpha(alpha);
invalidate();
}
}
public void setInteractiveUpdateRateMs(long updateRateMs) {
if (updateRateMs == mInteractiveUpdateRateMs) {
return;
}
mInteractiveUpdateRateMs = updateRateMs;
// Stop and restart the timer so the new update rate takes effect immediately.
if (shouldTimerBeRunning()) {
updateTimer();
}
}
private String formatTwoDigitNumber(int hour) {
return String.format("%02d", hour);
}
#Override
public void onDraw(Canvas canvas, Rect bounds) {
long now = System.currentTimeMillis();
int width = bounds.width();
int height = bounds.height();
mCalendar.setTimeInMillis(now);
mDate.setTime(now);
boolean is24Hour = DateFormat.is24HourFormat(CustomWatchFaceService.this);
// Draw the background.
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint);
//Draw the background Image
if (mBackgroundBitmap == null
|| mBackgroundBitmap.getWidth() != width
|| mBackgroundBitmap.getHeight() != height) {
mBackgroundBitmap = Bitmap.createScaledBitmap(mBackgroundBitmap,
width, height, true /* filter */);
}
//Log.d("XXX", "Width: "+ mBackgroundBitmap.getWidth() + "Height: "+mBackgroundBitmap.getHeight() );
if (isInAmbientMode() && (mLowBitAmbient)) {
canvas.drawColor(Color.BLACK);
} else if (isInAmbientMode()) {
canvas.drawColor(Color.BLACK);
} else {
canvas.drawBitmap(mBackgroundBitmap, 0, 0, mBackgroundPaint);
}
// Show colons for the first half of each second so the colons blink on when the time updates.
mShouldDrawColons = (System.currentTimeMillis() % 1000) < 500;
// Draw the hours.
float x = mXOffset;
String hourString;
if (is24Hour) {
hourString = formatTwoDigitNumber(mCalendar.get(Calendar.HOUR_OF_DAY));
} else {
int hour = mCalendar.get(Calendar.HOUR);
if (hour == 0) {
hour = 12;
}
hourString = String.valueOf(hour);
}
canvas.drawText(hourString, x, mYOffset, mHourPaint);
x += mHourPaint.measureText(hourString);
// In ambient and mute modes, always draw the first colon. Otherwise, draw the
// first colon for the first half of each second.
if (isInAmbientMode() || mMute || mShouldDrawColons) {
canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint);
}
x += mColonWidth;
// Draw the minutes.
String minuteString = formatTwoDigitNumber(mCalendar.get(Calendar.MINUTE));
canvas.drawText(minuteString, x, mYOffset, mMinutePaint);
x += mMinutePaint.measureText(minuteString);
// In unmuted interactive mode, draw a second blinking colon followed by the seconds.
// Otherwise, if we're in 12-hour mode, draw AM/PM
if (!isInAmbientMode() && !mMute) {
if (mShouldDrawColons) {
canvas.drawText(COLON_STRING, x, mYOffset, mColonPaint);
}
x += mColonWidth;
canvas.drawText(formatTwoDigitNumber(
mCalendar.get(Calendar.SECOND)), x, mYOffset, mSecondPaint);
} else if (!is24Hour) {
x += mColonWidth;
}
// Only render the day of week and date if there is no peek card, so they do not bleed
// into each other in ambient mode.
if (getPeekCardPosition().isEmpty()) {
// Day of week
canvas.drawText(
mDayOfWeekFormat.format(mDate),
mXOffset, mYOffset + mLineHeight, mDatePaint);
// Date
canvas.drawText(
mDateFormat.format(mDate),
mXOffset, mYOffset + mLineHeight * 2, mDatePaint);
}
}
/**
* Starts the {#link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "updateTimer");
}
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {#link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
}
}

How do I switch the components from a character motor to a character controller?

I am trying to code some underwater functionality for my Unity game, but I am having trouble switching the CharacterMotor components to the CharacterController ones. This is my code:
#pragma strict
var waterLevel : float;
var myParticles : ParticleSystem;
private var isUnderwater : boolean;
private var normalColor : Color;
private var underwaterColor : Color;
private var charcontroller:CharacterController;
function Start ()
{
normalColor = new Color (0.5f, 0.5f, 0.5f, 0.5f);
underwaterColor = new Color (0.22f, 0.65f, 0.77f, 0.5f);
charcontroller = GetComponent(CharacterController);
myParticles.Stop();
GameObject.Find("Blob Light Projector").GetComponent(Projector).enabled = false;
}
function Update ()
{
if ((transform.position.y < waterLevel) != isUnderwater)
{
isUnderwater = transform.position.y < waterLevel;
if (isUnderwater) SetUnderwater ();
if (!isUnderwater) SetNormal ();
}
if(isUnderwater && Input.GetKey(KeyCode.E))
{
constantForce.relativeForce = Vector3(0,-200, 0);
}
else
{
constantForce.relativeForce = Vector3(0, 0, 0);
}
if(isUnderwater && Input.GetKey(KeyCode.Q))
{
constantForce.relativeForce = Vector3(0, 200, 0);
}
}
function SetNormal ()
{
RenderSettings.fogColor = normalColor;
RenderSettings.fogDensity = 0.05f;
GameObject.Find("Blob Light Projector").GetComponent(Projector).enabled = false;
}
**function SetUnderwater ()
{
RenderSettings.fogColor = underwaterColor;
RenderSettings.fogDensity = 0.08f;
charcontroller.Move.gravity = 2;
charcontroller.Move.maxFallSpeed = 5;
charcontroller.Move.maxForwardSpeed = 4;
charcontroller.Move.maxSidewaysSpeed = 4;
myParticles.Play();
GameObject.Find("Blob Light Projector").GetComponent(Projector).enabled = true;
}**
The bolded code is where the error is coming from. Here is a snapshot of the errors I'm getting:
Any help would be really appreciated! Thanks!
You're trying to set properties on CharacterController.Move, which is a function. It doesn't reflect the "movement" property of CharacterMotor.
Check out the script reference and manual to see how to use CharacterController. Specifically, you'll be calling Move with a simple Vector3, and relying on the physics system to take care of the rest.

Using a external Spinner control in Windows Mobile 6.0

I am using slideUI controls in my project . There is a spinner control which is used as wait cursor. I want to display the spinner when I load data in a List.
But when I try to display the spinner it visualize as an image not a rotating image.
Below is my code.
private void uiButton_Click(object sender, EventArgs e)
{
ShowFrame(this.uiPanel1);
Application.DoEvents();
LoadList();
HideFrame(uiPanel1);
}
private void LoadList()
{
try
{
//Call the BeginAddControls before starting manipulations with UIList
uiList1.BeginAddControls();
for (int i = 0; i < 100; i++)
{
UIListItem item = new UIListItem();
item.Text = "Primary Text" + i;
item.SecondaryText = "This is secondary text..";
item.ItemStyle = UIListItemStyle.SingleText;
item.Height = Utils.CalcScaleSize(38);
item.BackColor = System.Drawing.SystemColors.Window;
item.BackEndColorSelected = System.Drawing.SystemColors.Highlight;
item.BackStartColorSelected = System.Drawing.SystemColors.Highlight;
item.BottomBorderColor = System.Drawing.Color.Gainsboro;
item.Buffering = true;
item.ColorScheme = SlideUI.UIColorSchemesCustom.Orange;
item.Dock = System.Windows.Forms.DockStyle.Top;
item.GroupArrowColor = System.Drawing.Color.Gray;
item.GroupArrowColorSelected = System.Drawing.Color.White;
item.IconQVGA = null;
item.IconSize = new System.Drawing.Size(25, 31);
item.IconTransparent = false;
item.IconTransparentColor = System.Drawing.Color.Transparent;
item.IconVGA = null;
item.IconVisible = true;
item.InheritParentSettings = true;
item.IsGroup = false;
item.IsSelected = false;
item.SecondaryTextColor = System.Drawing.SystemColors.GrayText;
item.SecondaryTextColorSelected = System.Drawing.SystemColors.HighlightText;
item.SecondaryTextFont = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular);
item.TextColor = System.Drawing.SystemColors.WindowText;
item.TextColorSelected = System.Drawing.SystemColors.HighlightText;
item.TextFont = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
item.UseGradient = true;
item.VirtualBufferRendered = false;
uiList1.AddControl(item);
}
//Call of EndAddControls method when the UIListItems binding is done
uiList1.EndAddControls();
//HideFrame(uiPanel1);
//ShowFrame(this.panel1, "Panel1");
}
catch (Exception ex)
{
UIMessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK,
UIMessageIcons.Done, UIColorSchemesCustom.Orange);
}
}
private void ShowFrame(Panel panel)
{
Panel pnlPanel = new Panel();
pnlPanel = panel;
//pnlPanel.Location = new System.Drawing.Point(0, 0);
pnlPanel.Show();
pnlPanel.BringToFront();
}
private void HideFrame(Panel panel)
{
Panel pnlPanel = new Panel();
pnlPanel = panel;
pnlPanel.Hide();
}
Thanks in advance

Java - I think my boolean is defaulting to true for some reason

I'm having an issue with my hangman program. When I run it, the label holding the int variable "lives" is supposed to update when you guess a wrong letter. But for some reason it isn't. I've placed this in my code as a test mechanism, and it isn't appearing even here.
if (used[letter] = false) {
System.out.println("test");
However, when I place it here.. It DOES work..
if (finished == false) {
boolean found = false;
boolean www = false;
System.out.println("test");
if (used[letter] = false) {
It almost leads me to believe that used[letter] is true by default, when it really shouldn't be. The variable is declared at the very top. Any thoughts?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
public class Hangman implements ActionListener {
JFrame frame;
JPanel stats = new JPanel();
JLabel currentWordLA = new JLabel("Current word:");
JLabel triedLettersLA = new JLabel("Tried letters:");
JLabel triesLeftLA = new JLabel("Tries remaining:");
private String[] wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday" };
public String mysteryWord;
public int lives;
private boolean finished = false;
private boolean won = false;
private Button a[];
public boolean used[] = new boolean[26];
public static void main (String[] args) {
Hangman gui = new Hangman();
gui.go();
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
setBackground(Color.white);
g.setColor(Color.gray);
g.fillRect(50, 200, 150, 20);
g.fillRect(90,20,10,200);
g.fillRect(90,20,60,10);
g.setColor(Color.black);
g.fillRect(145,20,5,25);
g.setColor(Color.green);
if (lives < 6 )
g.drawOval(132,45,30,30);
if (lives < 5 )
g.drawLine(147,75,147,100);
if (lives < 4 )
g.drawLine(147,100,167,133);
if (lives < 3 )
g.drawLine(147,100,127,133);
if (lives < 2 )
g.drawLine(147,75,167,85);
if (lives < 1 )
g.drawLine(147,75,127,85);
StringBuffer guessed = new StringBuffer();
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (used[(int)mysteryWord.charAt(cl)-'a'])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append("*");
}
currentWordLA.setText("Current word: " + guessed.toString());
if (lives < 1) {
g.setColor(Color.white);
g.fillRect(70, 200, 200, 30);
g.setColor(Color.black);
g.drawString(mysteryWord.toString(),75,230);
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
g.setColor(Color.red);
g.drawString("You lose!",200,100);
//finished = true;
}
if (won) {
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
// Color red=new Color.red
g.setColor(Color.red);
g.drawString("You Win!",200,100);
//finished = true;
}
}
}
public void go() {
///////////////////////DESIGN BEGIN//////////////////////////////////////////////
frame = new JFrame("Hangman");
JPanel topPanel = new JPanel();
myDrawPanel noosePanel = new myDrawPanel();
JPanel bottomPanel = new JPanel();
JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridLayout( 2, 0) );
bottomPanel.setLayout( new GridLayout( 0, 2) );
scorePanel.setSize(20,100);
noosePanel.setBorder(BorderFactory.createTitledBorder("Your progress."));
topPanel.setBorder(BorderFactory.createTitledBorder("Your arsenal."));
scorePanel.setBorder(BorderFactory.createTitledBorder("Your score."));
frame.add(topPanel);
frame.add(bottomPanel);
bottomPanel.add(scorePanel);
bottomPanel.add(noosePanel);
//Just the stats panel.
JButton restart = new JButton("Reset");
currentWordLA.setFont(new Font("Verdana", Font.PLAIN, 10));
currentWordLA.setForeground(Color.black);
triedLettersLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triedLettersLA.setForeground(Color.black);
triesLeftLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triesLeftLA.setForeground(Color.black);
restart.setFont(new Font("Verdana", Font.PLAIN, 16));
restart.setForeground(Color.red);
stats.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20,0,0,0);
c.anchor = GridBagConstraints.LINE_START;
stats.add(currentWordLA, c);
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triedLettersLA, c);
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triesLeftLA, c);
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
stats.add(restart, c);
scorePanel.add(stats);
///////////////////////DESIGN END//////////////////////////////////////////////
///////////////////////ALPHABET BEGIN//////////////////////////////////////////
int i;
StringBuffer buffer;
a = new Button[26];
topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
for (i = 0; i <26; i++) {
buffer = new StringBuffer();
buffer.append((char)(i+'a'));
a[i] = new Button(buffer.toString());
a[i].setSize(100,100);
a[i].addActionListener( this );
topPanel.add(a[i]);
}
///////////////////////ALPHABET END//////////////////////////////////////////
//Just shows the entire window.
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
//////////////////////GAMEPLAY BEGIN////////////////////////////////////////
lives = 6;
triesLeftLA.setText("Tries remaining: " + lives);
mysteryWord = wordGen();
}
//Returns a random word from the wordList bank.
private String wordGen() {
return wordList[0 + (int)(Math.random() * ((63 - 0) + 1)) ]; //Make sure to set these to nonprinted chars eventually
}
public void consultWord(int letter) {
if (finished == false) {
boolean found = false;
boolean www = false;
if (used[letter] = false) {
System.out.println("test");
for (int cl = 0 ; cl < mysteryWord.length(); cl++) {
if (mysteryWord.charAt(cl)==((char)(letter + 'a'))) {
found = true;
}
}
if (found == false) {
lives = lives - 1;
triesLeftLA.setText ("Tries remaining: " + lives);
}
}
used[letter] = true;
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (!used[(int)(mysteryWord.charAt(cl)) - 'a']){
www = true;
}
}
if (www == false) {
won = true;
}
frame.repaint();
}
}
public void actionPerformed( ActionEvent e) {
int i;
for (i = 0; i < 26; i++) {
if (e.getSource() == a[i]) {
consultWord(i); }
}
}
}
Make that:
if (used[letter] == false) {
System.out.println("test");
if (used[letter] = false) {
You just set used[letter] to false. Try ==
Of course, to avoid this typo you shouldn't be using == but rather ...
if (!used[letter]) {