Every time I try to run the application with the list view in a location in crashes or when i get it working the list view doesnt show up iv tried changing where the list view comes ie after the first frame layout under the fullscreen content and after the frame layout full screen content controls and still cant get it working
here is the active view xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context=".ActiveCheatsView" >
<TextView
android:id="#+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:text="#string/ActiveCheats"
android:textColor="#000000"
android:textSize="50sp"
android:textStyle="bold" />
<!--
This FrameLayout insets its children based on system windows using
android:fitsSystemWindows.
-->
<ListView
android:id="#+id/Games"
android:layout_width="fill_parent"
android:layout_height="410dp" >
</ListView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<Button
android:id="#+id/Button01"
style="?buttonBarButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/Search" />
</LinearLayout>
</FrameLayout>
and here is the java view
package com.example.activecheats;
import com.example.activecheats.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class ActiveCheatsView extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_cheats_view);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.Button01).setOnTouchListener(
mDelayHideTouchListener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
private List<Games> gamesList= new ArrayList<Games>();
private List<Games> gamesList;
/** Called when the activity is first created. */
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the View layer
setContentView(R.layout.activity_active_cheats_view);
setTitle("ActiveCheats");
// Create Parser for games.xml
GamesParser GamesParser = new GamesParser();
InputStream inputStream = getResources().openRawResource(
R.layout.games);
// Parse the inputstream
GamesParser.parse(inputStream);
setGamesList(com.example.activecheats.GamesParser.getList());
// Create a customized ArrayAdapter
GamesArrayAdapter adapter = new GamesArrayAdapter(
getApplicationContext(), R.layout.games_listitem, countryList);
// Get reference to ListView holder
ListView lv = (ListView) this.findViewById(R.id.Games);
// Set the ListView adapter
lv.setAdapter(adapter);
}
public List<Games> getGamesList() {
return gamesList;
}
public void setGamesList(List<Games> gamesList) {
this.gamesList = gamesList;
}
}
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
try this in your xml file and in your Mianactivity should extend ListActivity
Related
I am currently using a switch in my Android application as sort of options in my settings class. However, when I change the state of the switch, from say false to true, and go back to the menu, and then go back to the settings activity, the state of the switch goes back to the default value. Is there a key line that basically saves the switch's state so that when a user returns to it, the state is the same? I don't think this question requires code, but if you think it's helpful, please let me know and I'll attach it. Thanks!
here is my activity code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.speedytext.Options" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginLeft="46dp"
android:layout_marginTop="48dp"
android:layout_toRightOf="#+id/textView1"
android:text="Switch" />
<Switch
android:id="#+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/switch1"
android:layout_below="#+id/switch1"
android:layout_marginTop="66dp"
android:text="Switch" />
</RelativeLayout>
here is my java code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
public class Options extends ActionBarActivity {
private static Switch ding;
private Switch countdown;
public static boolean isDingChecked;
public static boolean isCountdownChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
ding = (Switch) findViewById(R.id.switch1);
ding.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
isDingChecked = isChecked;
System.out.println(isDingChecked);
System.out.println(isDingChecked());
}
});
countdown = (Switch) findViewById(R.id.switch2);
countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
isCountdownChecked = isChecked;
System.out.println(isCountDownChecked());
}
});
isDingChecked = ding.isChecked();
isCountdownChecked= countdown.isChecked();
}
public static boolean isDingChecked()
{
return isDingChecked;
}
public static boolean isCountDownChecked()
{
return isCountdownChecked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In onCreate(), call setChecked() with your stored "is checked" value to set the default to whatever was stored previously.
Also, consider storing the settings to e.g. shared preferences. static variables do not persist over application relaunches and often make your code harder to maintain.
Shared Preference Class
public class AppPreferences {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String text, String Tag) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void clear()
{
prefsEditor.clear();
prefsEditor.commit();
}
}
Usage of Shared Preference in activity
AppPreferences appPref;
appPref = new AppPreferences(getApplicationContext(), "PREFS");
To save the state
When the state of the switch is changed save the state true or false to a tag in shared preference
You can use this line to save the state
appPref.SaveData("Value", "Tag");
so it will be like this for checked state appPref.SaveData("true", "state");
and appPref.SaveData("false", "state"); for unchecked state
in the oncreate of your activity get the value from the shared preference
using
appPref.getData("state");
if(appPref.getData("state").equals("true"))
{
//set ur switch button to checked state
}
else if(appPref.getData("state").equals("false"))
{
//set ur switch button to unchecked state
}
then check the result string for true or false
and set the switch accordingly
I'm fairly new to Java, and really new to Android development.
I am trying to make a Morse Code app, which will flash the user's entered message in Morse Code on the device's screen.
My problem is that I cannot find a way to pause the code to put the timings in.
I know that putting a wait() or sleep() straight in is out of the question. After some searching around the web, I found some code and implemented it into mine - here is m current code - this is just a countdown to test the waiting:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash);
// ALL THIS STUFF IS AUTO-GENERATED
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
// EVERYTHING UP TO HERE IS AUTO-GENERATED
final TextView currentLabel = (TextView) findViewById(R.id.labelCurrent);
final TextView totalLabel = (TextView) findViewById(R.id.labelTotal);
new Thread () {
public void run() {
currentLabel.setText("3");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentLabel.setText("2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentLabel.setText("1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
}.start();
}
When testing this code, I found that in the emulated AVD, it just goes straight back to the MainActivity, and when I generated an APK and tested it on my device, the app crashed.
Any help is appreciated.
EDIT 1- Here's the logcat:
08-09 15:42:29.054 2012-2012/com.example.nat.morseflasher D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
08-09 15:42:38.564 2012-2012/com.example.nat.morseflasher D/dalvikvm﹕ GC_FOR_ALLOC freed 143K, 8% free 3195K/3444K, paused 142ms, total 183ms
08-09 15:42:55.654 2012-2012/com.example.nat.morseflasher I/Choreographer﹕ Skipped 31 frames! The application may be doing too much work on its main thread.
08-09 15:42:56.294 2012-2012/com.example.nat.morseflasher I/Choreographer﹕ Skipped 47 frames! The application may be doing too much work on its main thread.
08-09 15:43:07.725 2012-2012/com.example.nat.morseflasher I/Choreographer﹕ Skipped 1159 frames! The application may be doing too much work on its main thread.
EDIT 2:
Ok, so I've implemented the code you provided into mine, although I changed some things so it fits with how I want it.
When I try to run this, the log shows the "Starting morse code flasher..." message, but it never gets to the printing letter or symbol parts. When I tap the ready button, nothing changes at all, and it just goes back to the main activity as defined in the onPostExecute function.
Here's the XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099cc"
tools:context="com.example.nat.morseflasher.FlashActivity">
<!-- The primary full-screen view. This can be replaced with whatever view
is needed to present your content, e.g. VideoView, SurfaceView,
TextureView, etc. -->
<TextView android:id="#+id/fullscreen_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
android:textColor="#33b5e5"
android:textStyle="bold"
android:textSize="50sp"
android:gravity="center"
android:text="#string/dummy_content"
android:background="#000000" />
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#000000"
android:id="#+id/frameLayout">
<LinearLayout android:id="#+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="#color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent">
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="-"
android:id="#+id/labelCurrent"
android:layout_gravity="center"
android:layout_marginBottom="40dp"
android:textSize="100sp"
android:textColor="#ffffff" />
<TextView
android:layout_width="fill_parent"
android:layout_height="60dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Ready?"
android:id="#+id/labelTotal"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:textSize="25sp"
android:gravity="center_horizontal"
android:textIsSelectable="false"
android:textColor="#ffffff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tapToGo"
android:id="#+id/buttonGo"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="35dp"
android:onClick="doMorse" />
</FrameLayout>
</FrameLayout>
Here's the java:
package com.example.nat.morseflasher;
import com.example.nat.morseflasher.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FlashActivity extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
private final static String TAG = "FlashActivity";
private final static long TIME_UNIT = 250L;
private final static long ONE_SECOND = 1000L;
private final static long DOT_DELAY = TIME_UNIT;
private final static long DASH_DELAY = TIME_UNIT * 2;
private final static long INTRA_LETTER_DELAY = TIME_UNIT;
private final static long INTER_LETTER_DELAY = TIME_UNIT * 2;
private final static long INTER_WORD_DELAY = TIME_UNIT * 6;
Button goButton;
FrameLayout layoutFrame;
TextView currentLabel, totalLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
goButton = (Button) findViewById(R.id.buttonGo);
layoutFrame = (FrameLayout) findViewById(R.id.frameLayout);
currentLabel = (TextView) findViewById(R.id.labelCurrent);
totalLabel = (TextView) findViewById(R.id.labelTotal);
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
public void doMorse(View vw) {
goButton.setVisibility(View.GONE);
(new DoMorseFlashing()).execute();
}
private class DoMorseFlashing extends AsyncTask <String, Boolean, Void> {
SharedPreferences mPrefs = getSharedPreferences("MorseFlasher", Context.MODE_PRIVATE);
String msgStr, currentLetterMorse;
#Override
protected Void doInBackground(String... message) {
Log.v(TAG, "Starting Morse Code flasher...");
msgStr = mPrefs.getString("prevMsg", "");
String totalStr = "";
/*currentLabel.setText("3");
*doDelay(ONE_SECOND);
*currentLabel.setText("2");
*doDelay(ONE_SECOND);
*currentLabel.setText("1");
*doDelay(ONE_SECOND);
*/
for(int i=0; i<msgStr.length(); i++) {
if(msgStr.charAt(i)=='|') {
doDelay(INTER_WORD_DELAY);
}
else {
currentLetterMorse = convert(msgStr.charAt(i));
currentLabel.setText(msgStr.substring(i, i + 1));
totalStr += msgStr.substring(i, i + 1);
totalLabel.setText(totalStr);
Log.v(TAG, " flashing letter " + msgStr.charAt(i) + " with morse code " + currentLetterMorse + ":");
for (int j = 0; j < currentLetterMorse.length(); j++) {
Log.v(TAG, "flashing symbol " + currentLetterMorse.charAt(j) + ":");
flash(currentLetterMorse.charAt(j));
doDelay(INTRA_LETTER_DELAY);
}
doDelay(INTER_LETTER_DELAY);
}
}
return null;
}
protected void onPostExecute(Void result) {
// Set the button message back to "touch here" to indicate that were done flashing:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
void flash(char letter) {
layoutFrame.setBackgroundColor(Color.WHITE);
currentLabel.setTextColor(Color.BLACK);
totalLabel.setTextColor(Color.BLACK);
switch (letter) {
case '.':
doDelay(DOT_DELAY);
case '-':
doDelay(DASH_DELAY);
}
layoutFrame.setBackgroundColor(Color.BLACK);
currentLabel.setTextColor(Color.WHITE);
totalLabel.setTextColor(Color.WHITE);
}
String convert(char letter){
switch (letter){
case 'a':
return ".-";
case 'b':
return "-…";
case 'c':
return "-.-.";
case 'd':
return "-..";
case 'e':
return ".";
case 'f':
return "..-.";
case 'g':
return "--.";
case 'h':
return "….";
case 'i':
return "..";
case 'j':
return ".---";
case 'k':
return "-.-";
case 'l':
return ".-..";
case 'm':
return "--";
case 'n':
return "-.";
case 'o':
return "---";
case 'p':
return ".--.";
case 'q':
return "--.-";
case 'r':
return ".-.";
case 's':
return "...";
case 't':
return "-";
case 'u':
return "..-";
case 'v':
return "...-";
case 'w':
return ".--";
case 'x':
return "-..-";
case 'y':
return "-.--";
case 'z':
return "--..";
case ' ':
return "|";
default:
return "|";
}
}
void doDelay(Long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// Ignore interruptions
}
}
}
}
And here's the LogCat:
08-10 18:30:43.856 2090-2090/com.example.nat.morseflasher D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
08-10 18:30:46.146 2090-2106/com.example.nat.morseflasher D/dalvikvm﹕ GC_FOR_ALLOC freed 146K, 8% free 3192K/3448K, paused 31ms, total 39ms
08-10 18:30:50.816 2090-2090/com.example.nat.morseflasher I/Choreographer﹕ Skipped 464 frames! The application may be doing too much work on its main thread.
08-10 18:31:04.116 2090-2090/com.example.nat.morseflasher I/Choreographer﹕ Skipped 69 frames! The application may be doing too much work on its main thread.
08-10 18:31:06.486 2090-2090/com.example.nat.morseflasher I/Choreographer﹕ Skipped 62 frames! The application may be doing too much work on its main thread.
08-10 18:31:11.176 2090-2090/com.example.nat.morseflasher I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
08-10 18:31:11.937 2090-2106/com.example.nat.morseflasher V/FlashActivity﹕ Starting Morse Code flasher...
08-10 18:31:13.437 2090-2090/com.example.nat.morseflasher I/Choreographer﹕ Skipped 109 frames! The application may be doing too much work on its main thread.
EDIT 3:
Ok, so the earlier problem was due to the fact that it wasn't retrieving my string from SharedPreferences, so just to make sure everything else worked, I set the message string to "test" in the code. Now, the problem is that when it goes to change the colour of the screen, I get an error saying that only the main thread that created the view hierarchy can touch its views.
EDIT 4:
I've fixed the error as aforementioned by using runOnUiThread() when I go to change the screen and text colours, the flashing now works!
The LogCat messages are telling you that your app is spending too much time on the main thread and starving the GUI of processing time.
If all you want to do is flash the screen, you could use a simple AsyncTask rather than all the complexity of your SystemUiHider.
Here's some code that shows how a background AsyncTask could be used using simple thread-sleeps to handle the timing. Since it's a background task, the sleeping won't interfere with the main GUI thread.
The main feature is that publishProgess() is called periodically to turn the flasher on or off. Note you can't make GUI changes from within the doInBackground() method stack, but can within the onProgessUpdate() and onPostExecute() ones. I used the same button for both starting and showing the flashing so that I could demonstrate using the onPostExecute() method to reset the button text.
You'll obviously need to add Morse code strings for the other letters and probably tweak the timing values to get things to look right.
MainActivity.java
package com.example.com;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
// String for LogCat documentation
private final static String TAG = "MainActivity";
// These define the lengths for the dots, dashes, and times in between:
private final static long TIME_UNIT = 250L;
private final static long DOT_DELAY = TIME_UNIT * 2;
private final static long DASH_DELAY = TIME_UNIT * 3;
private final static long INTRA_LETTER_DELAY = TIME_UNIT;
private final static long INTER_LETTER_DELAY = TIME_UNIT * 3;
private final static long INTER_WORD_DELAY = TIME_UNIT * 7;
private Button flasher = null;
private EditText message = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flasher = (Button) findViewById(R.id.flasher);
message = (EditText) findViewById(R.id.message);
}
public void doMorse(View vw) {
String messageStr = message.getText().toString();
if (messageStr.length() > 0) {
// This creates and starts a background task to do the flashing:
(new DoMorseFlashing()).execute(messageStr);
// Set the button message to indicate that we're flashing a message:
flasher.setText(R.string.flashing_message);
}
}
private class DoMorseFlashing extends AsyncTask <String, Boolean, Void> {
#Override
protected Void doInBackground(String... message) {
Log.v(TAG, "Starting Morse Code flasher...");
for (char letter : message[0].toCharArray()) {
if (letter == ' ')
doDelay(INTER_WORD_DELAY);
else
showLetter(letter);
}
return null;
}
protected void onProgressUpdate(Boolean... flasherOn) {
if (flasherOn[0])
flasher.setBackgroundColor(Color.BLUE);
else
flasher.setBackgroundColor(Color.WHITE);
}
protected void onPostExecute(Void result) {
// Set the button message back to "touch here" to indicate that we're done flashing:
flasher.setText(R.string.touch_here);
}
void showLetter(char letter) {
Log.v(TAG, "Flashing code for " + letter);
switch (letter) {
case 'A': showMorse(".-"); break;
case 'B': showMorse("-..."); break;
case 'C': showMorse("-.-."); break;
// cases for the other letters...
default: /* skip character */
}
doDelay(INTER_LETTER_DELAY);
}
void showMorse(String morse) {
Log.v(TAG, "Flashing code " + morse);
for (char dotDash: morse.toCharArray()) {
Log.v(TAG, "Flashing " + dotDash);
publishProgress(true);
if (dotDash == '.')
doDelay(DOT_DELAY);
else
doDelay(DASH_DELAY);
doDelay(INTRA_LETTER_DELAY);
publishProgress(false);
}
}
void doDelay(Long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// Ignore interruptions
}
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textCapCharacters"
android:hint="#string/enter_message" />
<Button
android:id="#+id/flasher"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top|center"
android:background="#android:color/background_light"
android:hint="#string/touch_here"
android:onClick="doMorse" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Morse Flasher</string>
<string name="enter_message">Enter message</string>
<string name="touch_here">Touch here to flash message</string>
<string name="flashing_message">Flashing message</string>
</resources>
So I created a new activity using the 'Fullscreen Activity' template in Android Studio. I now want to change the background which is set to android:background="#0099cc" by default in its generated XML file. However, I've tried the 'solution' on one of the more popular, similar questions but got a error.
How to set background color of an Activity to white programmatically?
The error I get is:
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:2060)
at android.content.res.Resources.getDrawable(Resources.java:1625)
at android.view.View.setBackgroundResource(View.java:16251)
which happens at the root.setBackgroundResource(Color.WHITE); line. Below is the entirety of the java code with the only two things added to the Activity template being the onStart method and a setActivityBackgroundColor() method.
package org.test.app;
import org.test.app.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.test.app.R;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivityTest extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_activity_test);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);
}
protected void onStart() {
super.onStart();
setActivityBackgroundColor();
}
public void setActivityBackgroundColor() {
setContentView(R.layout.activity_fullscreen_activity_test);
View root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
root.setBackgroundResource(Color.WHITE);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
setBackgroundResource takes a resource, not a color (even though both are integers). You probably want to use View.setBackgroundColor if you want to set it to a color in code.
I have a viewpager for a fullscreen image slider with horizontal swipe. What I am trying to do is put an image behind every image on the slider. Meaning, a user can click on a 'flip' button to reveal another image.
Below is my code however I have two issues:
The first time I click the flip button, it flips the image but only
to reveal the same image. However, when I click it the second time
it works :).
The flip button only works on the first image. When I swipe
right or left the flip button doesn't work anymore. Any help?
Note: I am using a fullscreenActivity theme which hides the UI control until the user clicks on the image.
FullscreenActivity.java
package me.zamaaan.wallpaper;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import me.zamaaan.wallpaper.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import static me.zamaaan.wallpaper.HeavyLifter.FAIL;
import static me.zamaaan.wallpaper.HeavyLifter.SUCCESS;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import java.util.ArrayList;
import java.util.List;
/** A helper class that will do the heavy work of decoding images and actually setting the wallpaper */
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class FullscreenActivity extends Activity implements OnClickListener, AnimationListener{
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
private HeavyLifter chuckNorris;
private Animation animation1;
private Animation animation2;
private boolean isBackOfCardShowing = true;
/*
an array with the ids of the images for the viewpager
*/
public Integer[] mImageIds = {
R.drawable.background1, R.drawable.background2,
R.drawable.background3, R.drawable.background4,
R.drawable.background1, R.drawable.background2,
R.drawable.background1, R.drawable.background2,
R.drawable.background3, R.drawable.background4,
R.drawable.background1, R.drawable.background2,
R.drawable.background3
};
/*
an array with the ids of the images for the back flip of each image in the viewpager
*/
public Integer[] mBackIds = {
R.drawable.splash, R.drawable.splash,
R.drawable.splash, R.drawable.splash,
R.drawable.splash, R.drawable.splash,
R.drawable.splash, R.drawable.splash,
R.drawable.splash, R.drawable.splash,
R.drawable.splash, R.drawable.splash,
R.drawable.splash
};
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
animation1 = AnimationUtils.loadAnimation(this, R.anim.to_middle);
animation1.setAnimationListener(this);
animation2 = AnimationUtils.loadAnimation(this, R.anim.from_middle);
animation2.setAnimationListener(this);
findViewById(R.id.flip).setOnClickListener(this);
// Loop through the ids to create a list of full screen image views
ImageAdapter imageAdapter = new ImageAdapter(this);
List<ImageView> images = new ArrayList<ImageView>();
for (int i = 0; i < imageAdapter.getCount(); i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setImageResource(imageAdapter.mThumbIds[i]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
images.add(imageView);
}
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.view_pager);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.btnSetAsWallpaper).setOnTouchListener(
mDelayHideTouchListener);
findViewById(R.id.btnSaveWallpaper).setOnTouchListener(
mDelayHideTouchListener);
// Finally create the adapter
ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(images);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(imagePagerAdapter);
// Set the ViewPager to point to the selected image from the previous activity
// Selected image id
int position = getIntent().getExtras().getInt("id");
viewPager.setCurrentItem(position);
//set title of Image
this.setTitle(imageAdapter.mThumbTitles[position]);
// Load are heavy lifter (goes and does work on another thread), to get a response after the lifters thread
// has finished we pass in a Handler that will be notified when it completes
chuckNorris = new HeavyLifter(this, chuckFinishedHandler);
}
#Override
public void onClick(View v) {
v.setEnabled(false);
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).clearAnimation();
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).setAnimation(animation1);
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).startAnimation(animation1);
}
#Override
public void onAnimationEnd(Animation animation) {
int i = getIntent().getExtras().getInt("id");
if (animation==animation1) {
if (isBackOfCardShowing) {
((ImageView)findViewById(i)).setImageResource(mImageIds[i]);
} else {
((ImageView)findViewById(i)).setImageResource(mBackIds[i]);
}
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).clearAnimation();
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).setAnimation(animation2);
((ImageView)findViewById(getIntent().getExtras().getInt("id"))).startAnimation(animation2);
} else {
isBackOfCardShowing=!isBackOfCardShowing;
findViewById(R.id.flip).setEnabled(true);
}
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
/**
* Called from XML when the save wallpaper button is pressed
* Thie retrieves the id of the current image from our list
* It then asks chuck to save it as a wallpaper!
* The chuckHandler will be called when this operation is complete
* #param v
*/
public void saveWallpaper(View v) {
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
// Show a toast message on successful save
if(chuckNorris.saveResourceAsWallpaper(imageAdapter.mThumbIds[position])){
Toast.makeText(FullscreenActivity.this, "Image Saved to ZamaaanWallpaper folder", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(FullscreenActivity.this, "Image couldn't be saved, try again", Toast.LENGTH_SHORT).show();
}
}
/**
* Called from XML when the set wallpaper button is pressed
* Thie retrieves the id of the current image from our list
* It then asks chuck to set it as a wallpaper!
* The chuckHandler will be called when this operation is complete
* #param v
*/
public void setAsWallpaper(View v) {
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
chuckNorris.setResourceAsWallpaper(imageAdapter.mThumbIds[position]);
}
/**
* This is the handler that is notified when are HeavyLifter is finished doing an operation
*/
private Handler chuckFinishedHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch(msg.what){
case SUCCESS:
Toast.makeText(FullscreenActivity.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
break;
case FAIL:
Toast.makeText(FullscreenActivity.this, "Wallper NOT set, try again", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
};
}
I fixed my issues. I simply had to :
Change the boolean isBackOfCardShowing to an array of boolean for each page and intialize it to false.
Use viewpager.getCurrentItem() to get the position of the current page instead of what I was doing.
I tried to run the code to test if the program works, but it doesn't seem to do anything. I am getting an error that the fullscreen_contents_controls can't be resolved (line 54) and a syntax error when I can't find one (line 100). Can you help debug it?
Here are the errors:
Description Resource Path Location Type
fullscreen_content_controls cannot be resolved or is not a field Opening.java /MagicSquaresGame/src/com/mtprogramming/magicsquaresgame line 54 Java Problem
Description Resource Path Location Type
Syntax error, insert "}" to complete MethodBody Opening.java /MagicSquaresGame/src/com/mtprogramming/magicsquaresgame line 100 Java Problem
Code:
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class Opening extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = false;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
Have you made sure that "fullscreen_content_controls" exists in your xml layout?
Your controlsView should have an id attribute
<controlsView
android:id='full_content_controls'
...
>