I created a game, where I rotate through multiple activitys. Each activity stays just for a few seconds. Now I should add ads to the game. Since it doesn't make sense if the ad refreshes after just a few seconds I have to create a view which stays alive the whole time even if I start a new activity.
Since a view is bind to an activity (?) it might not be possible. So I wonder wether there is another solution to keep the adView alive while the content views are rotating.
Thanks in advance.
Edit:
Here is a simple Activity which is part of the activity cycle:
public class Punish extends ActivityWithSound implements OnClickListener {
#SuppressWarnings("unused")
private final String TAG = "Punish";
private RelativeLayout buttonContainer;
private ImageView bgImg;
private TextView nameTxt;
private TextView questTxt;
private Button mainMenuBtn;
private Button okBtn;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
bundle = getIntent().getExtras();
if(bundle == null)
bundle = StbApp.getTempBundle();
setContentView(R.layout.quest);
setupView();
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
soundtrack.startFX(R.raw.fx_execution);
super.onResume();
}
#Override
protected void onPause() {
StbApp.getTempBundle().putInt(Victim.VICTIM, bundle.getInt(Victim.VICTIM));
soundtrack.stopAllFX();
super.onPause();
}
#Override
public void onClick(View view) {
if (view == mainMenuBtn){
//TODO Continue Function
Intent intent = new Intent(this, TitleScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
StbApp.setContinueBtn(true);
StbApp.getLastActivity().setClass(this, Punish.class);
startActivity(intent);
}
if (view == okBtn){
if (StbApp.getPenalty() == PenaltyType.LEAVE){
StbApp.getPlayer().remove(bundle.getInt(Victim.VICTIM));
StbApp.setNumberOfPlayer(StbApp.getNumberOfPlayer()-1);
}
if (StbApp.getNumberOfPlayer() == 2 && StbApp.getPenalty() == PenaltyType.LEAVE)
startActivity(new Intent(this, GameOver.class));
else {
startActivity(new Intent(this, Round.class));
}
}
}
#Override
public void onBackPressed() {
return;
}
private void setupView() {
float textSize = (float) getResources().getDimension(R.dimen.standard_text_size)/getResources().getDisplayMetrics().scaledDensity;
buttonContainer = (RelativeLayout) findViewById(R.id.container_button);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) findViewById(R.id.container_button).getLayoutParams();
params.setMargins(0, 0, 0, (int) (StbApp.AdHeight*1.3));
buttonContainer.setLayoutParams(params);
bgImg = (ImageView) findViewById(R.id.imgv_girl);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
nameTxt = (TextView) findViewById(R.id.text_victim_name);
Log.d(TAG, "PlayerSize " + StbApp.getPlayer().size());
Log.d(TAG, "PlayerIndex bundle.getInt(Victim.VICTIM) " + bundle.getInt(Victim.VICTIM));
nameTxt.setText(StbApp.getPlayer().get(bundle.getInt(Victim.VICTIM)).getName());
nameTxt.setTextSize(textSize);
questTxt = (TextView) findViewById(R.id.text_quest);
switch (StbApp.getPenalty()) {
case LEAVE:
questTxt.setText(getResources().getString(R.string.punish_leave));
break;
case DRNK:
questTxt.setText(getResources().getString(R.string.punish_drink));
break;
case UNDRESS:
questTxt.setText(getResources().getString(R.string.punish_undress));
break;
}
questTxt.setTextSize(textSize);
mainMenuBtn = (Button) findViewById(R.id.button_mainmenu);
mainMenuBtn.setOnClickListener(this);
okBtn = (Button) findViewById(R.id.button_ok);
okBtn.setOnClickListener(this);
}
#Override
protected void onDestroy() {
if (bgImg.getDrawable() != null){
bgImg.getDrawable().setCallback(null);
bgImg.setImageDrawable(null);
}
super.onDestroy();
}
What I need would be an alternative for onDestroy, onPause and onResume.
A solution could be using a ViewFlipper/ViewSwitcher instead of jumping activities and then placing the adsView over or under the ViewFlipper/ViewSwitcher - It will however probably require quite a large re-write of your app.
Related
I have a simple program that changes the background of activity A from activity B.
When you change the background you need to refresh activity A in order for the background to change, after looking around stackoverflow the easiest way was just to call recreate().
I'm not sure if im calling it wrong or in the wrong area but what ends up happening is it will loop the following error when the app is run and eventually crash-
02-01 13:23:53.358 17302-17302/com.package.www.randomapp E/ViewRootImpl: sendUserActionEvent() mView == null
Here's the code for activity A
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
backgroundChanger();
recreate();
}
public void backgroundChanger(){
SharedPreferences sharedGradients = getSharedPreferences("gradientInfo", Context.MODE_PRIVATE);
int backgroundGrad = sharedGradients.getInt("backgroundGradient", 0);
if (backgroundGrad == 0){
MMBackground.setBackgroundResource(R.drawable.blackgreengradiant);
}
if (backgroundGrad == 1){
MMBackground.setBackgroundResource(R.drawable.blueblackgradiant);
}
if (backgroundGrad == 2){
MMBackground.setBackgroundResource(R.drawable.goldblackgradiant);
}
and for Activity B
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_menu);
variableHandler();
}
public void variableHandler() {
MainMenuBackgroundBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final SharedPreferences[] sharedGradients = {getSharedPreferences("gradientInfo", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editor1 = {sharedGradients[0].edit()};
final SharedPreferences[] sharedBoolean = {getSharedPreferences("binaryPoint", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editorBinary = {sharedBoolean[0].edit()};
final PopupMenu popup = new PopupMenu(getApplicationContext(), v);
popup.inflate(R.menu.menu_background_gradiant_setter);
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(OptionsMenu.this, "Blue and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 1);
editor1[0].apply();
return true;
case R.id.item2:
Toast.makeText(OptionsMenu.this, "Gold and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 2);
editor1[0].apply();
return true;
}
}
The problem is that you are calling recreate() in the onCreate() method of the Activity without any condition which will create an infinite loop. Keep a variable to track whether the activity is recreated or not.
private static boolean alreadyRecreated = false;
//You can add some extra conditions here if you want.
if(!alreadyRecreated){
recreate();
alreadyRecreated = true;
}
recreate(); will cause your activity to be recreated.
i.e, onCreate gets called. Since, you added recreate(); in onCreate method, it is running into infinite loop and crashing.
Any idea how to illustrate backspace funtion in this code? I try to make some changes but it can't work the backspace function. So, i would like to help me, with the backspace button.
enter code here
public class MainActivity extends AppCompatActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonBackspace).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonSquared) != null) {
findViewById(R.id.buttonSquared).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonSine) != null) {
findViewById(R.id.buttonSine).setOnClickListener(this);
}
if (findViewById(R.id.buttonCosine) != null) {
findViewById(R.id.buttonCosine).setOnClickListener(this);
}
if (findViewById(R.id.buttonTangent) != null) {
findViewById(R.id.buttonTangent).setOnClickListener(this);
}
}
#Override
public void onClick (View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
}
userIsInTheMiddleOfTypingANumber = true;
}else{
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
if (new Double(mCalculatorBrain.getResult()).equals(0.0)) {
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
if (new Double(mCalculatorBrain.getResult()).equals(0.0)){
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
In your layout you can add a onClick attribute to each button, say onClick="function", and in your activity you just need to implement a method like this:
public void function(View v) {
switch(v.getId()) {
case R.id.buttonBackspace:
// handle the backspace button
break;
case R.id.xxx:
// handle the button
break;
...
}
}
And for digits, I suggest assign a tag to each digit button in the layout, and do your logic in java based on the tag, instead of the text on the button. Because the text is just a UI, it might change in the future due to other possible requirements.
I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")
I got a problem with a quite large GridView.(about 70 children) The GridView works fine if I start it on onCreate or after resumeing after pressing the home button and then return. But when I resume after coming back from sleep mode, my BaseAdapter starts again and ruin the changes I have done to it during runtime. This also make getChildAt() give a NullPointerException if I am calling it just after restart.
How can I make it just do what regular onPause(home button) does to the GridView, and avoid that the GridView is wiped out everytime I am resumeing from sleep mode?
Edit:
I have tried setting a wakelock for my Activity class that calls the BaseAdpter with no luck
2.Edit: Since I posted this question I have played around with trying to restore the GridView using this code in onPause:
SparseArray<Parcelable> array = new SparseArray<Parcelable>();
gridView.saveHierarchyState(array);
bundle = new Bundle();
bundle.putSparseParcelableArray("state", array);
And this in onResume:
try{
gridView.restoreHierarchyState(bundle.getSparseParcelableArray("state"));
}
catch(Exception e){
//Most likely first start
Log.i("SomeTag", "No GridView state found");
}
}
The strange thing is everything I seems to have jumped from one place to another on the screen and it is still crashing when I try to getChildAt(). It is also failing to get it after sleep mode.
Edit Here is the code from BaseAdapter getView(Note! some of this code is irrelevant)
public View getView (int position, View convertView, ViewGroup parent) {
mParentView = parent;
DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
//sets the height for every individual box
int box = width/7*6/10;
ImageCell v = null;
if (convertView == null) {
// If it's not recycled, create a new ImageCell.
v = new ImageCell (mContext);
v.setLayoutParams(new GridView.LayoutParams(box, box));
v.setScaleType(ImageView.ScaleType.CENTER_CROP);
v.setPadding(0, 0, 0, 0);
} else {
v = (ImageCell) convertView;
}
v.mCellNumber = position;
v.mGrid = (GridView) mParentView;
v.mEmpty = true;
int id = 200;
v.setId(++id);
String map = str[position];
int pos = position;
int up = pos-10;
int down = pos+10;
int left = pos-1;
int right = pos+1;
if(up>=0){
above = str[up];
}
else{
//Do nothing
}
if(down<70){
under = str[down];
}
else{
//Do nothing
}
if(left<=-1){
//Do nothing
}
else{
lefte=str[left];
}
if(right>=70){
//Do nothing
}
else{
righte=str[right];
}
//if(left>-1|left!=9|left!=19|left!=29|left!=39|left!=49|left!=59){
// lefte = str[left];
// }
// else{
// Log.i("ImageCellAdapter", "Left is trying to break walls "+left);
//Do nothing
// }
if (map.equals("mountain")) {
//Checks surroundings to find out witch drawable to set
v.setBackgroundResource(R.color.cell_empty);
v.mEmpty = false;
//All
if(above=="mountain"&&under=="mountain"&&lefte=="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_full);
}
//Single
else if(above=="mountain"&&under!="mountain"&&lefte!="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_down);
}
else if(above!="mountain"&&under=="mountain"&&lefte!="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_up);
}
else if(above!="mountain"&&under!="mountain"&&lefte!="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_left);
}
else if(above!="mountain"&&under!="mountain"&&lefte=="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_right);
}
//Double
else if(above=="mountain"&&under!="mountain"&&lefte!="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_left_down);
}
else if(above!="mountain"&&under=="mountain"&&lefte!="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_left_up);
}
else if(above=="mountain"&&under!="mountain"&&lefte=="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_right_down);
}
else if(above!="mountain"&&under=="mountain"&&lefte=="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_up_right);
}
else if(above!="mountain"&&under!="mountain"&&lefte=="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_up_down);
}
else if(above=="mountain"&&under=="mountain"&&lefte!="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_up_down);
}
//Triple
else if(above!="mountain"&&under=="mountain"&&lefte=="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_left_right_down);
}
else if(above=="mountain"&&under=="mountain"&&lefte=="mountain"&&righte!="mountain"){
v.setImageResource(R.drawable.mountain_left_up_down);
}
else if(above=="mountain"&&under!="mountain"&&lefte=="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_left_up_right);
}
else if(above=="mountain"&&under=="mountain"&&lefte!="mountain"&&righte=="mountain"){
v.setImageResource(R.drawable.mountain_up_right_down);
}
//None
else{
v.setImageResource(R.drawable.mountain);
}
}
else if(map=="start"){
List<String> posOf = Arrays.asList(str);
startPos=posOf.indexOf("start");
v.mEmpty=false;
v.setBackgroundResource(R.color.cell_empty);
getDur();
BitmapDrawable first = (BitmapDrawable)mContext.getResources().getDrawable(R.drawable.gress);
BitmapDrawable second =(BitmapDrawable)mContext.getResources().getDrawable(R.drawable.ic_launcher);
BitmapDrawable third = (BitmapDrawable)mContext.getResources().getDrawable(R.drawable.gress);
BitmapDrawable fourth = (BitmapDrawable)mContext.getResources().getDrawable(R.drawable.ic_launcher);
final AnimationDrawable ani = new AnimationDrawable();
ani.addFrame(first, duration);
ani.addFrame(second, duration);
ani.addFrame(third, duration);
ani.addFrame(fourth, duration);
ani.setOneShot(true);
v.setImageDrawable(ani);
checkIfAnimationDone(ani);
v.post(new Runnable() {
public void run() {
ani.start();
}
});
}
else if(map=="stop"){
v.mEmpty=false;
v.setBackgroundResource(R.color.cell_empty);
v.setImageResource(R.drawable.ic_launcher);
v.setTag(1);
}
else if(map=="grass"){
v.mEmpty=false;
v.setBackgroundResource(R.drawable.gress);
}
else{
// v.setBackgroundResource (R.color.drop_target_enabled);
v.setBackgroundResource (R.color.cell_empty);
}
//v.mGrid.requestDisallowInterceptTouchEvent (true);
//v.setImageResource (R.drawable.hello);
// Set up to relay events to the activity.
// The activity decides which events trigger drag operations.
// Activities like the Android Launcher require a long click to get a drag operation started.
return v;
}
And defining the GridView in onCreate:
gridView= new BoxView(this);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
int width = Measuredwidth/7*6;
gridView.setLayoutParams(new GridView.LayoutParams(width,LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));
gridView.setNumColumns(columns);
gridView.setVerticalSpacing(0);
gridView.setHorizontalSpacing(0);
gridView.setPadding(0, 0, 0, 0);
gridView.setId(101);
gridView.setSelector(android.R.color.transparent);
gridView.setAdapter (new ImageCellAdapter(this, MAP));
I have noticed one thing in you code:
gridView.setLayoutParams(new GridView.LayoutParams(width,LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));
Even if GridView is a ViewGroup, you can't access it's LayoutParams. Just think it trough, if this would be possible that means you could put a GridView inside another GridView.
Fix this before going further because is messing with you.
If you want your GridView to be inside a LinearLayout, for example, try this:
gridView.setLayoutParams(new LinearLayout.LayoutParams(width,LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));
Here is the correct implementation of this answer:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*You have to implement what things from the gridView sould be "saved"*/
GridView gridView = new GridView(this) {
#Override
public Parcelable onSaveInstanceState() {
// Create the Parceable object with the things you want to save
Parceable stateOfGrid = ....etc
return stateOfGrid;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
// Restore your grid's parameters that you previously implemented in onSaveInstanceState
super.onRestoreInstanceState(state);
...
}
};
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
Parcelable state = savedInstanceState.getParcelable("state");
if (state != null) {
gridView.onRestoreInstanceState(state);
Log.d(this.getClass().getName(), "state restored!");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Put your grid's Parceable into the bundle
super.onSaveInstanceState(outState);
Parcelable state = gridView.onSaveInstanceState();
outState.putParcelable("state", state);
}
}
Try using this tag:
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
You can use onSaveInstanceState (Bundle outState)
to save state of your gridview
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Parcelable state = gridView.onSaveInstanceState();
outState.putParcelable("state", state);
}
then in onCreate after you seted adapter to grdiview add this code
if (savedInstanceState != null) {
Parcelable state = savedInstanceState.getParcelable("state");
if (state != null) {
gridView.onRestoreInstanceState(state);
Log.d(this.getClass().getName(), "state restored!");
}
}
Is your application running in Landscape Mode?
if yes, then you should consider adding the tag
"android:configChanges="keyboard|keyboardHidden|orientation" for your activity in Manifest.xml, which will prevent android system from killing your activity and restarting it when you unlock the screen.
I'm trying to use setText to show different text within the same layout everytime someone clicks a different picture.
So all the layout files stay the same the only thing that needs to change is the android:text in that layout.
I've created a class with case statement for when someone presses on a picture and then call setText().
But it looks like the setText isn't even called. because I can see my Log.v that is called within the same case statement but the text doesn't change.
PictureInfo.java
public class PictureInfo extends Activity implements OnClickListener {
private static final String TAG = "Popup";
public TextView infoText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
infoText = (TextView)inflater.inflate(R.layout.information, null);
View a1Button = findViewById(R.id.a1);
a1Button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.a1:
Intent a = new Intent(this, Information.class);
startActivity(a);
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
break;
}
}
}
information.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/information_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/a1_text"
/>
It appears that you are inflating a layout - R.layout.information, but casting this to a TextView. I'm really not sure what you are doing there.
I think you want the destination Activity to use some text in its layout that the source Activity provides to it. Why not pass the id of the text you want displayed as an Extra on the Intent?
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.a1:
Intent a = new Intent(this, Information.class);
intent.putExtra("com.packagename.identifier", R.string.a2_text);
startActivity(a);
break;
}
}
Then in your Information Activity:
public class Information extends Activity {
...
TextView myTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
...
myTextView = (TextView) findViewById(R.id.myTextViewId);
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
int textId = extras.getInt("com.packagename.identifier");
infoText.setText(textId);
}
}
}
Change the order of the code to:
//First change text
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
//Then call new activity
Intent a = new Intent(this, Information.class);
startActivity(a);
And voilá!