uso studio propiedades personalizado imagenes example descargar con columnas android gridview lifecycle android-gridview baseadapter

studio - propiedades gridview android



Mantenga GridView al reanudar desde el modo de suspensiĆ³n (4)

¿Tu aplicación se está ejecutando en modo horizontal?

Si es así, entonces debería considerar agregar la etiqueta

"android:configChanges="keyboard|keyboardHidden|orientation" para su actividad en Manifest.xml, que evitará que el sistema Android mate su actividad y la reinicie al desbloquear la pantalla.

Tengo un problema con un GridView bastante grande (alrededor de 70 niños). El GridView funciona bien si lo inicio onCreate o después de reanudarlo después de presionar el botón de inicio y luego regresar. Pero cuando reanudo el trabajo después de regresar del modo de suspensión, mi BaseAdapter se inicia de nuevo y arruina los cambios que le he hecho durante el tiempo de ejecución. Esto también hace que getChildAt () dé una NullPointerException si la llamo justo después de reiniciar.

¿Cómo puedo hacer que solo haga lo que normalmente usa OnPause (botón de inicio) para GridView, y evitar que GridView desaparezca cada vez que estoy reanudando desde el modo de suspensión?

Editar: He intentado configurar un wakelock para mi clase de actividad que llama al BaseAdpter sin suerte

2.Editar: Desde que publiqué esta pregunta, he jugado con intentar restaurar el GridView usando este código en onPause:

SparseArray<Parcelable> array = new SparseArray<Parcelable>(); gridView.saveHierarchyState(array); bundle = new Bundle(); bundle.putSparseParcelableArray("state", array);

Y esto en onResume:

try{ gridView.restoreHierarchyState(bundle.getSparseParcelableArray("state")); } catch(Exception e){ //Most likely first start Log.i("SomeTag", "No GridView state found"); } }

Lo extraño es todo lo que parece haber saltado de un lugar a otro en la pantalla y todavía se cuelga cuando intento getChildAt (). Tampoco está obteniendo después del modo de suspensión.

  1. Editar Aquí está el código de BaseAdapter getView (Nota: parte de este código es irrelevante)

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;

}

Y definiendo el GridView en 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));


Intenta usar esta etiqueta:

android:configChanges="keyboard|keyboardHidden|orientation|screenSize"


Me he dado cuenta de algo en tu código:

gridView.setLayoutParams(new GridView.LayoutParams(width,LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));

Incluso si GridView es un ViewGroup , no puede acceder a LayoutParams . Solo piénselo, si esto fuera posible, eso significa que podría poner un GridView dentro de otro GridView .

Arregle esto antes de ir más allá porque está jugando con usted.

Si quiere que su GridView esté dentro de LinearLayout, por ejemplo, intente esto:

gridView.setLayoutParams(new LinearLayout.LayoutParams(width,LayoutParams.FILL_PARENT, Gravity.CENTER_HORIZONTAL));

Aquí está la implementación correcta de esta respuesta :

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); } }


Puede usar onSaveInstanceState (Bundle outState) para guardar el estado de su gridview

@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Parcelable state = gridView.onSaveInstanceState(); outState.putParcelable("state", state); }

luego en onCreate después de que hayas propuesto el adaptador a grdiview agrega este código

if (savedInstanceState != null) { Parcelable state = savedInstanceState.getParcelable("state"); if (state != null) { gridView.onRestoreInstanceState(state); Log.d(this.getClass().getName(), "state restored!"); } }