Autore Topic: Problema con cast di una View[Fragment]  (Letto 1130 volte)

Offline MisterAnt

  • Utente normale
  • ***
  • Post: 272
  • Respect: +4
    • IlSikano
    • Mostra profilo
  • Dispositivo Android:
    Galaxy S4 Active,Galaxy SIII I9300, Galaxy Tab GT-P5100
  • Play Store ID:
    MisterAnt
  • Sistema operativo:
    Ubuntu 12.04/Winzoz 7/Winzoz xp
Problema con cast di una View[Fragment]
« il: 23 Agosto 2013, 15:22:38 CEST »
0
Salve a tutti =)
Ho un errore quando vado a impostare il mio adapter nella griglia...La sto usando all'interno di un Fragment
Codice: [Seleziona]
08-23 13:19:32.975: W/dalvikvm(31220): threadid=1: thread exiting with uncaught exception (group=0x412f3300)
08-23 13:19:32.985: E/AndroidRuntime(31220): FATAL EXCEPTION: main
08-23 13:19:32.985: E/AndroidRuntime(31220): java.lang.ClassCastException: android.app.Application cannot be cast to android.view.View$OnTouchListener
08-23 13:19:32.985: E/AndroidRuntime(31220):         at com.blahti.example.drag3.ImageCellAdapter.getView(ImageCellAdapter.java:106)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.AbsListView.obtainView(AbsListView.java:2267)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.GridView.onMeasure(GridView.java:1030)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1020)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.LinearLayout.onMeasure(LinearLayout.java:576)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.View.measure(View.java:15190)
08-23 13:19:32.985: E/AndroidRuntime(31220):         at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4817)

MIO ADAPTER
Codice (Java): [Seleziona]
   public ImageCellAdapter(Context c) {
    mContext = c;
}

/**
 */

// Methods

/**
 * getCount
 */


public int getCount() {
    Resources res = mContext.getResources();
    CaricaNDrink();    
    int numImages = numero_drink;
    return numImages;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return position;
}

/**
 * getView
 * Return a view object for the grid.
 *
 * @return ImageCell
 */

public View getView (int position, View convertView, ViewGroup parent) {
    mParentView = parent;

    ImageCell v = null;
    if (convertView == null) {
        // If it's not recycled, create a new ImageCell.
        v = new ImageCell (mContext);
        v.setLayoutParams(new GridView.LayoutParams(cell_w,cell_h));//(145, 145));//85,85
        //v.setScaleType(ImageView.ScaleType.CENTER_CROP);//ScaleType.CENTER_CROP);
        v.setPadding(pad/*left*/, pad2/*top*/, pad/*right*/, pad2/*bottom*/);//tutto 8
        v.setBackgroundResource(R.drawable.coffe_background);

    } else {
        v = (ImageCell) convertView;
    }

    v.mCellNumber = position;
    v.mGrid = (GridView) mParentView;
    v.mEmpty = true;
//    v.setBackgroundResource (R.color.drop_target_enabled);
    v.setBackgroundResource (R.drawable.black);

    //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.
    v.setOnTouchListener ((View.OnTouchListener) mContext); //riga 106
    v.setOnClickListener ((View.OnClickListener) mContext);
    v.setOnLongClickListener ((View.OnLongClickListener) mContext);

    return v;
}
Se le zampe del coniglio sono così fortunate, che fine ha fatto il coniglio?

Offline matttt

Re:Problema con cast di una View[Fragment]
« Risposta #1 il: 23 Agosto 2013, 15:33:35 CEST »
0
Come ti dice l'eccezione non puoi convertire un Context in un OnTouchListener.
Cosa vuoi fare di preciso?

Potresti fare un unico Listener che implementa le 3 interfaccie richieste.
Istanziarlo.
E poi passare quell'oggetto a quelle funzioni.
Le mie apps su Google Play Store:

Offline MisterAnt

  • Utente normale
  • ***
  • Post: 272
  • Respect: +4
    • IlSikano
    • Mostra profilo
  • Dispositivo Android:
    Galaxy S4 Active,Galaxy SIII I9300, Galaxy Tab GT-P5100
  • Play Store ID:
    MisterAnt
  • Sistema operativo:
    Ubuntu 12.04/Winzoz 7/Winzoz xp
Re:Problema con cast di una View[Fragment]
« Risposta #2 il: 23 Agosto 2013, 15:48:36 CEST »
0
Volevo instanziare la mia griglia con quei specifici oggetti..sull'activity funziona...ma sul fragment che è la copia quasi uguale no...
Posto la mia classe non del tutto completa...cmq è una galleria drag and drop con sotto una griglia.. e dei bottoni a lato per ridimensionare
Codice (Java): [Seleziona]
public class FragmentLayout extends Fragment
                implements View.OnLongClickListener, View.OnClickListener,View.OnTouchListener {

       
                private SharedPreferences prefs_dati;
                private final static String MY_PREFERENCES_DATI = "FileSettings";
                private final static String TEXT_DATA_KEY_DATI="info_file";
                private  String SetDati;
       
       
                private View myFragmentView;
                private Context ctx;
       
       
                private int numero_drink_attivi;
                private int numero_drink;
       
       
                private Integer[] mImageIds = {
                R.drawable.df;
                R.drawable.df2;
                   R.drawable.df3;
                R.drawable.df4;
                   
            };
       
                private RelativeLayout mainRelativeLayout;
                private HorizontalListView lvPicture;
                private ItemAdapter itemAdapter;
                private DragController mDragController;   // Object that handles a drag-drop sequence. It intersacts with DragSource and DropTarget objects.
                private DragLayer mDragLayer;             // The ViewGroup within which an object can be dragged.
                private DeleteZone mDeleteZone;
                private boolean mLongClickStartsDrag = false;   // If true, it takes a long click to start the drag operation.
                private ImageCellAdapter adapter;
                public static final boolean Debugging = false;   // Use this to see extra toast messages.
                private ImageView imageDrag;
                private OneItem oneItemSelected;
                private int mImageCount = 0;  // The number of images that have been added to screen.
                private ImageCell mLastNewCell = null;  
               

       
       
               
                private  FrameLayout image;
                private GridView gridView;
               
               
                private Button btn1,btn2,btn3,btn4;
                private Button btn;
                private RelativeLayout btn32,btn42,btn43,btn53;
               
               
                private int x=0,y=0;
                private int position;
               
                private ImageCell newView;
               
       
               
               
       
       
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
                          // TODO Auto-generated method stub
                          myFragmentView = inflater.inflate(R.layout.set_layout_x2, container, false);
                          return myFragmentView;
        }
       
/////////////////////////////////////////////////////////////////
       
       
        public void onActivityCreated(Bundle savedInstanceState){
                super.onActivityCreated(savedInstanceState);
                ///////////////////////////////////////////
                ctx=getActivity().getApplicationContext();
                position=0;
            btn32=(RelativeLayout)myFragmentView.findViewById(R.id.grid_3_2);
            btn42=(RelativeLayout)myFragmentView.findViewById(R.id.grid_4_2);
            btn43=(RelativeLayout)myFragmentView.findViewById(R.id.grid_4_3);
            btn53=(RelativeLayout)myFragmentView.findViewById(R.id.grid_5_3);
            btn1=(Button)myFragmentView.findViewById(R.id.btn_3_2);
            btn2=(Button)myFragmentView.findViewById(R.id.btn_4_2);
            btn3=(Button)myFragmentView.findViewById(R.id.btn_4_3);
            btn4=(Button)myFragmentView.findViewById(R.id.btn_5_3);
            btn = (Button)myFragmentView.findViewById(R.id.button_add_image);
            btn.setVisibility(View.GONE);
            ////////////////////////////////
            btn32.setBackgroundResource(R.drawable.orange_border);
                btn42.setBackgroundResource(R.drawable.orange_border);
                btn43.setBackgroundResource(R.drawable.orange_border);
                btn53.setBackgroundResource(R.drawable.orange_border);
                btn32.setBackgroundColor(Color.TRANSPARENT);
                btn42.setBackgroundColor(Color.TRANSPARENT);
                btn43.setBackgroundColor(Color.TRANSPARENT);
                btn53.setBackgroundColor(Color.TRANSPARENT);
                Lista=new DrinkList();
                ////////////////////
       
               
                // View.OnLongClickListener, View.OnClickListener,View.OnTouchListener
               
                /*myFragmentView.setOnClickListener(FragmentLayout.this);
                myFragmentView.setOnLongClickListener(FragmentLayout.this);
                myFragmentView.setOnTouchListener(FragmentLayout.this);*/

               
                InizializzaGriglia();  
                CaricaGriglia();
                ///////////////////
            mDeleteZone = (DeleteZone)myFragmentView.findViewById (R.id.delete_zone_view);
            mDeleteZone.setVisibility(View.GONE);
            /////////////////////////////////////
            image = (FrameLayout)myFragmentView.findViewById (R.id.frame_img);
            image.setVisibility(View.GONE);
            ////////////////////
            mainRelativeLayout=(RelativeLayout)myFragmentView.findViewById(R.id.view_movable);
            lvPicture = (HorizontalListView)mainRelativeLayout.findViewById(R.id.listView1);
            itemAdapter = new ItemAdapter(ctx, constructList());
                lvPicture.setAdapter(itemAdapter);
                lvPicture.setOnItemSelectedListener(mOnItemSelectedListener);
                lvPicture.setOnItemMoveListener(mOnItemMoveListener);
                lvPicture.setOnTouchListener(new OnTouchListener(){
                        public boolean onTouch(View arg0, MotionEvent arg1) {
                                x = (int)arg1.getRawX();
                            y = (int)arg1.getRawY();
                                return mLongClickStartsDrag;
                               
                        }
                });
               
        }

       
//////////////////////////////////////////////////////////////
       
       
       
        public void CaricaGriglia(){
                numero_drink_attivi=Lista.getBottoni_attivi();
                switch(numero_drink_attivi){
                  case 6://ok
                        InizializzaGriglia();
                        btn1.getBackground().setAlpha(255);
                        btn2.getBackground().setAlpha(45);
                        btn3.getBackground().setAlpha(45);
                        btn4.getBackground().setAlpha(45);
                        ///////////////////////////////////
                        btn32.setBackgroundResource(R.drawable.orange_border);
                        btn42.setBackgroundColor(Color.TRANSPARENT);
                        btn43.setBackgroundColor(Color.TRANSPARENT);
                        btn53.setBackgroundColor(Color.TRANSPARENT);
                        /////////////////////////
                        CaricaNDrink();
                    n_drink="6";
                    SaveNDrink();
                    gridView.setNumColumns(3);
                    adapter.setCell_h(266);//250 255
                    adapter.setCell_w(260);//266
                    adapter.setPad(220);
                    adapter.setPad2(300);
                        break;
                case 8://ok
                        InizializzaGriglia();
                        btn32.setBackgroundColor(Color.TRANSPARENT);
                        btn42.setBackgroundResource(R.drawable.orange_border);
                        btn43.setBackgroundColor(Color.TRANSPARENT);
                        btn53.setBackgroundColor(Color.TRANSPARENT);
                        ////////////////////////////////
                        btn1.getBackground().setAlpha(45);
                        btn2.getBackground().setAlpha(255);
                        btn3.getBackground().setAlpha(45);
                        btn4.getBackground().setAlpha(45);
                        //////////////////
                        CaricaNDrink();
                    n_drink="8";
                    SaveNDrink();
                    gridView.setNumColumns(4);
                    adapter.setCell_h(266);
                    adapter.setCell_w(195);
                    adapter.setPad(120);
                    adapter.setPad2(300);
                        break;
                case 12://ok
                        InizializzaGriglia();
                        btn32.setBackgroundColor(Color.TRANSPARENT);
                        btn42.setBackgroundColor(Color.TRANSPARENT);
                        btn43.setBackgroundResource(R.drawable.orange_border);
                        btn53.setBackgroundColor(Color.TRANSPARENT);
                        /////////////////////////////////////
                        btn1.getBackground().setAlpha(45);
                        btn2.getBackground().setAlpha(45);
                        btn3.getBackground().setAlpha(255);
                        btn4.getBackground().setAlpha(45);
                        btn43.setBackgroundResource(R.drawable.orange_border);
                        ////////////////////
                        CaricaNDrink();
                    n_drink="12";
                    SaveNDrink();
                    gridView.setNumColumns(4);
                    adapter.setCell_h(177);
                    adapter.setCell_w(195);
                    adapter.setPad(80);
                    adapter.setPad2(80);
                        break;
                case 15:
                        InizializzaGriglia();
                        btn32.setBackgroundColor(Color.TRANSPARENT);
                        btn42.setBackgroundColor(Color.TRANSPARENT);
                        btn43.setBackgroundColor(Color.TRANSPARENT);
                        btn53.setBackgroundResource(R.drawable.orange_border);
                        btn1.getBackground().setAlpha(45);
                        btn2.getBackground().setAlpha(45);
                        btn3.getBackground().setAlpha(45);
                        btn4.getBackground().setAlpha(255);
                        btn53.setBackgroundResource(R.drawable.orange_border);
                        /////////////////////////////////////
                        CaricaNDrink();
                    n_drink="15";
                    SaveNDrink();
                    gridView.setNumColumns(5);
                    adapter.setCell_h(177);
                    adapter.setCell_w(156);
                    adapter.setPad(70);
                    adapter.setPad2(70);
                    NumeroDeiDrink(15);
                    SetLayout();
                        break;
                }

        }
//////////////////////////////////////////////////////////////////////////////////
       
       
        public void onClickGriglia (View v) {
                LinearLayout.LayoutParams params;
                switch(v.getId()){
                        case R.id.btn_3_2://ok
                                InizializzaGriglia();
                                btn1.getBackground().setAlpha(255);
                                btn2.getBackground().setAlpha(45);
                                btn3.getBackground().setAlpha(45);
                                btn4.getBackground().setAlpha(45);
                                ///////////////////////////////////////
                                btn32.setBackgroundResource(R.drawable.orange_border);
                                btn42.setBackgroundColor(Color.TRANSPARENT);
                                btn43.setBackgroundColor(Color.TRANSPARENT);
                                btn53.setBackgroundColor(Color.TRANSPARENT);
                                /////////////////////////
                                CaricaNDrink();
                            n_drink="6";
                            SaveNDrink();
                            gridView.setNumColumns(3);
                            adapter.setCell_h(266);//250 255
                            adapter.setCell_w(260);//266
                            adapter.setPad(220);
                            adapter.setPad2(300);
                            NumeroDeiDrink(6);
                            SetLayout();
                                break;
                        case R.id.btn_4_2://ok
                                InizializzaGriglia();
                                btn32.setBackgroundColor(Color.TRANSPARENT);
                                btn42.setBackgroundResource(R.drawable.orange_border);
                                btn43.setBackgroundColor(Color.TRANSPARENT);
                                btn53.setBackgroundColor(Color.TRANSPARENT);
                                ///////////////////////////////////////
                                btn1.getBackground().setAlpha(45);
                                btn2.getBackground().setAlpha(255);
                                btn3.getBackground().setAlpha(45);
                                btn4.getBackground().setAlpha(45);
                                //////////////////
                       
                            n_drink="8";
                            SaveNDrink();
                            gridView.setNumColumns(4);
                            adapter.setCell_h(266);
                            adapter.setCell_w(195);
                            adapter.setPad(120);
                            adapter.setPad2(300);
                            NumeroDeiDrink(8);
                            SetLayout();
                                break;
                        case R.id.btn_4_3://ok
                                InizializzaGriglia();
                                btn32.setBackgroundColor(Color.TRANSPARENT);
                                btn42.setBackgroundColor(Color.TRANSPARENT);
                                btn43.setBackgroundResource(R.drawable.orange_border);
                                btn53.setBackgroundColor(Color.TRANSPARENT);
                                ////////////////////////////////////////////
                                btn1.getBackground().setAlpha(45);
                                btn2.getBackground().setAlpha(45);
                                btn3.getBackground().setAlpha(255);
                                btn4.getBackground().setAlpha(45);
                                btn43.setBackgroundResource(R.drawable.orange_border);
                                ////////////////////
                                CaricaNDrink();
                            n_drink="12";
                            SaveNDrink();
                            gridView.setNumColumns(4);
                            adapter.setCell_h(177);
                            adapter.setCell_w(195);
                            adapter.setPad(80);
                            adapter.setPad2(80);
                            NumeroDeiDrink(12);
                            SetLayout();
                                break;
                        case R.id.btn_5_3:
                                InizializzaGriglia();
                                btn32.setBackgroundColor(Color.TRANSPARENT);
                                btn42.setBackgroundColor(Color.TRANSPARENT);
                                btn43.setBackgroundColor(Color.TRANSPARENT);
                                btn53.setBackgroundResource(R.drawable.orange_border);
                                /////////////////////////////////////////////
                                btn1.getBackground().setAlpha(45);
                                btn2.getBackground().setAlpha(45);
                                btn3.getBackground().setAlpha(45);
                                btn4.getBackground().setAlpha(255);
                                btn53.setBackgroundResource(R.drawable.orange_border);
                                /////////////////////////////////////
                                CaricaNDrink();
                            n_drink="15";
                            SaveNDrink();
                            gridView.setNumColumns(5);
                            adapter.setCell_h(177);
                            adapter.setCell_w(156);
                            adapter.setPad(70);
                            adapter.setPad2(70);
                            NumeroDeiDrink(15);
                            SetLayout();
                                break;
            }
        }
///////////////////////////////////////////////////////////////////////
       
       
        public void InizializzaGriglia(){
                int cont=0;
                Log.i("BUG",""+cont);cont++;//1
                gridView = (GridView)myFragmentView.findViewById(R.id.image_grid_view);
                Log.i("BUG",""+cont);cont++;//2
            gridView.setNumColumns(4);
            Log.i("BUG",""+cont);cont++;//3
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) gridView.getLayoutParams();
            params.width = 790;
            params.height = 610;
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.setMargins(0, 20, 0, 10);//params.setMargins(0, 60, 0, 20);
            Log.i("BUG",""+cont);cont++;//4
            gridView.setLayoutParams(params);
            Log.i("BUG",""+cont);cont++;//5
            if (gridView == null) ;//toast ("Unable to find GridView");
            else {
                 adapter=new ImageCellAdapter(getActivity());
                 try{
                                //gridView.setAdapter (adapter);
                 }catch(Exception xx){
                         Toast.makeText(ctx, "E:"+xx, Toast.LENGTH_LONG).show();
                 }
            }
            Log.i("BUG",""+cont);cont++;//6
            mDragController = new DragController(ctx);
            Log.i("BUG",""+cont);cont++;//7
            mDragLayer = (DragLayer)myFragmentView.findViewById(R.id.drag_layer);
            Log.i("BUG",""+cont);cont++; //8
            mDragLayer.setDragController (mDragController);
            Log.i("BUG",""+cont);cont++;//9
            mDragLayer.setGridView (gridView);
            Log.i("BUG",""+cont);cont++;//10
            mDragController.setDragListener (mDragLayer);
            Log.i("BUG",""+cont);cont++;//11
           
        }
///////////////////////////////////////////////////////////////////////////////
                               


///////////////////////////////////////////////////////////////////////////////
       

       
/////////////////////////////////////////////////////////////////////

        /**
         * Send a message to the debug log. Also display it using Toast if Debugging is true.
         */

       

//////////////////////////////////////////////////                             
       

       
//////////////////////////////////////////////////////////////
       
       
        /**
         * Start dragging a view.
         *
         */
   

        public boolean startDrag (View v){
            DragSource dragSource = (DragSource) v;
            // We are starting a drag. Let the DragController handle it.
            Log.i("StartDrag Function ","in uso");
            mDragController.startDrag (v, dragSource, dragSource, DragController.DRAG_ACTION_MOVE);
                image.setVisibility(View.GONE);    
                        //Animation scaleAnimation = new ScaleAnimation(1, (float) 0.5, 1, (float) 0.5, 150, 100);
                        //scaleAnimation.setDuration(3800);
                        //a.startAnimation(scaleAnimation);
            return true;
        }
       
       
       
       
/**
 * This is the starting point for a drag operation if mLongClickStartsDrag is false.
 * It looks for the down event that gets generated when a user touches the screen.
 * Only that initiates the drag-drop sequence.
 *
 */
 
       
        public boolean onTouch(View v, MotionEvent ev) {
                // If we are configured to start only on a long click, we are not going to handle any events here.
            if (mLongClickStartsDrag) return false;

            boolean handledHere = false;
            final int action = ev.getAction();
            ImageCell i = (ImageCell) v;
            // In the situation where a long click is not needed to initiate a drag, simply start on the down event.
            if (action == MotionEvent.ACTION_DOWN) {
                Log.i("onTouch Function 1"," METTILO QUI");
               handledHere = startDrag (v);
            }
            Log.i("onTouch Function 2"," in uso");
            ///
           
            int nn=Integer.parseInt(n_drink);
            GridView g= (GridView) mDragLayer.getGridView();
                for(int j=0;j<=nn-1;j++){
                        ImageCell a=(ImageCell)g.getChildAt(j);
                        int h = a.getHeight();
                        int b = a.getWidth();
                        //Animation scaleAnimation = new ScaleAnimation(1, (float) 0.5, 1, (float) 0.5, 150, 100);
                        //scaleAnimation.setDuration(3800);
                        //a.startAnimation(scaleAnimation);
                }
            return handledHere;
        }

public void onClick(View v) {
        // TODO Auto-generated method stub
       
}

/**
 * Handle a long click.
 * If mLongClick only is true, this will be the only way to start a drag operation.
 *
 * @param v View
 * @return boolean - true indicates that the event was handled
 */


        public boolean onLongClick(View v) {
                if (mLongClickStartsDrag) {
                //trace ("onLongClick in view: " + v + " touchMode: " + v.isInTouchMode ());
                // Make sure the drag was started by a long press as opposed to a long click.
                // (Note: I got this from the Workspace object in the Android Launcher code.
                //  I think it is here to ensure that the device is still in touch mode as we start the drag operation.)
                if (!v.isInTouchMode()) {
                   //toast ("isInTouchMode returned false. Try touching the view again.");
                   return false;
                }
                return startDrag (v);
            }

            // If we get here, return false to indicate that we have not taken care of the event.
            return false;
        }
//////////////////////////////////////////////////////////////////////////////
       
        private AdapterView.OnItemSelectedListener mOnItemSelectedListener = new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
                       
                        /**
                         * retrieve selected item from adapterview
                         */

                        oneItemSelected = (OneItem) arg0.getItemAtPosition(arg2);
                        //Toast.makeText(getApplicationContext(), "posiz: "+arg2,Toast.LENGTH_SHORT).show();
                        position=arg2;
                        //image.setVisibility(View.GONE);
                       
                        DragDrop();
                       
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                       
                }

        };
       
//////////////////////////////////////////////////////////////////////////////////////////
       
       
        public void DragDrop(){
                if(image!=null){
                //int resource=DrinkSelector();
                //image.setBackgroundDrawable(getResources().getDrawable(resource));
                           //position=Integer.parseInt(""+posiz);
                           //Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_SHORT).show();
                           //image.removeAllViews();
                           image.setVisibility(View.VISIBLE);
                           //arg0.setVisibility(View.GONE);
                           //image.setScaleType(ImageView.ScaleType.FIT_XY);
                        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams (200,200,Gravity.CENTER);
                        RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) image.getLayoutParams();

                        if(y>70){
                                y=100;
                        }
                                layout.leftMargin = (int) x - image.getWidth()/2;              
                                layout.topMargin = (int) y - image.getHeight()/2;
                                image.setLayoutParams(layout);
                       
                       newView = new ImageCell (getActivity());
                       //int resource=DrinkSelector();
                       Bitmap bm=null;
                       bm=DrinkSelectorExternal();
                       //newView.setImageResource (resource);
                       newView.setImageBitmap(bm);
                       image.addView (newView, layout);
                       newView.mEmpty = false;
                       newView.mCellNumber = -1;
                       mLastNewCell = newView;
                       mImageCount++;
                       // Have this activity listen to touch and click events for the view.
                       
                       newView.setOnClickListener(FragmentLayout.this);
                       newView.setOnLongClickListener(FragmentLayout.this);
                       newView.setOnTouchListener (FragmentLayout.this);
             }else{
                 image.setVisibility(View.GONE);
             }
        }

       
       
//////////////////////////////////////////////////////////////////////////////
       
                               
        private OnTouchListener mOnItemMoveListener = new  OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                        RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) image.getLayoutParams();
                        image.setVisibility(ImageView.VISIBLE);
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                image.bringToFront();
                                return true;
                        }
                        if (event.getAction()==MotionEvent.ACTION_MOVE) {
                                //layout.leftMargin = (int) event.getX() - newView.getWidth()/2;               
                                ///layout.topMargin = (int) event.getY() - newView.getHeight()/2;
                        }
                        if (event.getAction()==MotionEvent.ACTION_UP) {
                                image.setVisibility(View.GONE);
                        }
                        image.setLayoutParams(layout);
                        return true;
                }

        };
Se le zampe del coniglio sono così fortunate, che fine ha fatto il coniglio?

Offline matttt

Re:Problema con cast di una View[Fragment]
« Risposta #3 il: 23 Agosto 2013, 15:56:51 CEST »
0
Ora mi è più chiaro :)

Secondo me non hai bisogno di fare un cast del context.

Invece di passare il Context nel costruttore:
Codice (Java): [Seleziona]
public ImageCellAdapter(Context c)Potresti passare FragmentLayout.
Tenerti un riferimento al Fragment "padre".
Passare quel riferimento ai vari set listener.

Credo funzioni poi.
Le mie apps su Google Play Store:

Offline MisterAnt

  • Utente normale
  • ***
  • Post: 272
  • Respect: +4
    • IlSikano
    • Mostra profilo
  • Dispositivo Android:
    Galaxy S4 Active,Galaxy SIII I9300, Galaxy Tab GT-P5100
  • Play Store ID:
    MisterAnt
  • Sistema operativo:
    Ubuntu 12.04/Winzoz 7/Winzoz xp
Re:Problema con cast di una View[Fragment]
« Risposta #4 il: 23 Agosto 2013, 16:31:51 CEST »
0
Quasi risolto..grazie...adesso non crasha più quando viene instanziato l'adapter ma crasha quando vado a fare il drag and drop XD
Codice: [Seleziona]
08-23 14:30:24.695: E/InputEventReceiver(1874): Exception dispatching input event.
08-23 14:30:24.695: E/MessageQueue-JNI(1874): Exception in MessageQueue callback: handleReceiveCallback
08-23 14:30:24.715: E/MessageQueue-JNI(1874): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.ViewRootImpl.setView(ViewRootImpl.java:585)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at com.blahti.example.drag3.DragView.show(DragView.java:159)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at com.blahti.example.drag3.DragController.startDrag(DragController.java:234)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at com.blahti.example.drag3.DragController.startDrag(DragController.java:176)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at com.gestione.keyslayout.FragmentLayout.startDrag(FragmentLayout.java:657)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at com.gestione.keyslayout.FragmentLayout.onTouch(FragmentLayout.java:685)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.View.dispatchTouchEvent(View.java:7126)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2179)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1880)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2179)
08-23 14:30:24.715: E/MessageQueue-JNI(1874):         at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1880)

DRAGVIEW
Codice (Java): [Seleziona]
/*
 * This is a modified version of a class from the Android Open Source Project.
 * The original copyright and license information follows.
 *
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.blahti.example.drag3;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

/**
 * A DragView is a special view used by a DragController. During a drag operation, what is actually moving
 * on the screen is a DragView. A DragView is constructed using a bitmap of the view the user really
 * wants to move.
 *
 */


public class DragView extends View {
    // Number of pixels to add to the dragged item for scaling.  Should be even for pixel alignment.
    private static final int DRAG_SCALE = 0;   // In Launcher, value is 40

    private Bitmap mBitmap;
    private Paint mPaint;
    private int mRegistrationX;
    private int mRegistrationY;

    private float mScale;
    private float mAnimationScale = 0.9f;

    private WindowManager.LayoutParams mLayoutParams;
    private WindowManager mWindowManager;

    /**
     * Construct the drag view.
     * <p>
     * The registration point is the point inside our view that the touch events should
     * be centered upon.
     *
     * @param context A context
     * @param bitmap The view that we're dragging around.  We scale it up when we draw it.
     * @param registrationX The x coordinate of the registration point.
     * @param registrationY The y coordinate of the registration point.
     */

    public DragView(Context context, Bitmap bitmap, int registrationX, int registrationY,
            int left, int top, int width, int height) {
        super(context);

        // mWindowManager = WindowManagerImpl.getDefault();
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);        
 
        Matrix scale = new Matrix();
        float scaleFactor = width ;
        scaleFactor = mScale = (scaleFactor + DRAG_SCALE) / scaleFactor;
        scale.setScale(scaleFactor, scaleFactor);
        mBitmap = Bitmap.createBitmap(bitmap, left, top, width, height, scale, true);

        // The point in our scaled bitmap that the touch events are located
        mRegistrationX = registrationX + (DRAG_SCALE / 2);
        mRegistrationY = registrationY + (DRAG_SCALE / 2);// div 2
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mBitmap.getWidth(), mBitmap.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint p2;
        if (true) {
            // Puts a little border around the view so you can see that you selected something.
            Paint p = new Paint();
            p.setStyle (Paint.Style.FILL);
            p.setColor(Color.TRANSPARENT);
            p.setAlpha (80);
            //getHeight
            //canvas.drawRect(0, 0, getWidth(), getHeight(), p);
        }
        float scale = mAnimationScale;
        if (scale < 0.999f) { // allow for some float error
            float height = mBitmap.getHeight();
            float width = mBitmap.getWidth();
            float offset1 = (width-(width*scale))/2;
            float offset2 = (height-(height*scale))/2;
            canvas.translate(offset1, offset2);
            canvas.scale(scale, scale);
        }
        p2 = new Paint();
        p2.setAlpha (100);
        canvas.drawBitmap(mBitmap, 0.0f, 0.0f, p2);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mBitmap.recycle();
    }

    public void setPaint(Paint paint) {
        mPaint = paint;
        invalidate();
    }

    public void setScale (float scale) {
        if (scale > 1.0f) mAnimationScale = 1.0f;
        else mAnimationScale = scale;
        invalidate();
    }

    /**
     * Create a window containing this view and show it.
     *
     * @param windowToken obtained from v.getWindowToken() from one of your views
     * @param touchX the x coordinate the user touched in screen coordinates
     * @param touchY the y coordinate the user touched in screen coordinates
     */

    public void show(IBinder windowToken, int touchX, int touchY) {
        WindowManager.LayoutParams lp;
        int pixelFormat;
        pixelFormat = PixelFormat.TRANSLUCENT;
        lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                touchX-mRegistrationX, touchY-mRegistrationY,
                WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                   /// | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, ///da togliere
                pixelFormat);
        lp.gravity = Gravity.LEFT | Gravity.TOP;
        lp.token = windowToken;
        lp.setTitle("DragView");
        mLayoutParams = lp;

        mWindowManager.addView(this, lp);

    }
   
    /**
     * Move the window containing this view.
     *
     * @param touchX the x coordinate the user touched in screen coordinates
     * @param touchY the y coordinate the user touched in screen coordinates
     */

    void move(int touchX, int touchY) {
        // This is what was done in the Launcher code.
        WindowManager.LayoutParams lp = mLayoutParams;
        lp.x = touchX - mRegistrationX;
        lp.y = touchY - mRegistrationY;
        mWindowManager.updateViewLayout(this, lp);
    }

    void remove() {
        mWindowManager.removeView(this);
    }
}
« Ultima modifica: 23 Agosto 2013, 16:33:46 CEST da MisterAnt »
Se le zampe del coniglio sono così fortunate, che fine ha fatto il coniglio?

Offline matttt

Re:Problema con cast di una View[Fragment]
« Risposta #5 il: 23 Agosto 2013, 17:05:45 CEST »
0
Difficile fare debugging via forum cmq eh :P

DragController.java:234 ? Qualche problema con quel primo parametro che passi a show() ? E' null per qualche motivo?
Le mie apps su Google Play Store:

Offline MisterAnt

  • Utente normale
  • ***
  • Post: 272
  • Respect: +4
    • IlSikano
    • Mostra profilo
  • Dispositivo Android:
    Galaxy S4 Active,Galaxy SIII I9300, Galaxy Tab GT-P5100
  • Play Store ID:
    MisterAnt
  • Sistema operativo:
    Ubuntu 12.04/Winzoz 7/Winzoz xp
Re:Problema con cast di una View[Fragment]
« Risposta #6 il: 23 Agosto 2013, 17:18:01 CEST »
0
Giusto :)
DRAGCONTROLLER
Codice (Java): [Seleziona]
/**
 * This class handles all touch events associated with a user
 * dragging a view around inside a ViewGroup.
 * When a drag starts, it creates a special view (a DragView) that moves around the screen
 * until the user ends the drag. As feedback to the user, this object causes the device to
 * vibrate as the drag begins. It interacts with other objects through methods defined
 * in the DropTarget and DragSource interfaces.
 *
 * <p> It also supports the DragListener interface for objects that want to be
 * notified when objects are dragged and dropped.
 *
 */


public class DragController {
    private static final String TAG = "DragController";

    /** Indicates the drag is a move.  */
    public static int DRAG_ACTION_MOVE = 0;

    /** Indicates the drag is a copy.  */
    public static int DRAG_ACTION_COPY = 1;

    private static final int VIBRATE_DURATION = 35;

    private static final boolean PROFILE_DRAWING_DURING_DRAG = false;

    private Context mContext;
    private Vibrator mVibrator;

    // temporaries to avoid gc thrash
    private Rect mRectTemp = new Rect();
    private final int[] mCoordinatesTemp = new int[2];

    /** Whether or not we're dragging. */
    private boolean mDragging;

    /** X coordinate of the down event. */
    private float mMotionDownX;

    /** Y coordinate of the down event. */
    private float mMotionDownY;

    /** Info about the screen for clamping. */
    private DisplayMetrics mDisplayMetrics = new DisplayMetrics();

    /** Original view that is being dragged.  */
    private View mOriginator;

    /** X offset from the upper-left corner of the cell to where we touched.  */
    private float mTouchOffsetX;

    /** Y offset from the upper-left corner of the cell to where we touched.  */
    private float mTouchOffsetY;

    /** Where the drag originated */
    private DragSource mDragSource;

    /** The data associated with the object being dragged */
    private Object mDragInfo;

    /** The view that moves around while you drag.  */
    private DragView mDragView;

    /** Who can receive drop events */
    private ArrayList<DropTarget> mDropTargets = new ArrayList<DropTarget>();

    private DragListener mListener;

    /** The window token used as the parent for the DragView. */
    private IBinder mWindowToken;

    private View mMoveTarget;

    private DropTarget mLastDropTarget;

    private InputMethodManager mInputMethodManager;

    /**
     * Interface to receive notifications when a drag starts or stops
     */

    interface DragListener {
       
        /**
         * A drag has begun
         *
         * @param source An object representing where the drag originated
         * @param info The data associated with the object that is being dragged
         * @param dragAction The drag action: either {@link DragController#DRAG_ACTION_MOVE}
         *        or {@link DragController#DRAG_ACTION_COPY}
         */

        public void onDragStart(DragSource source, Object info, int dragAction);
       
        /**
         * The drag has eneded
         */

        public void onDragEnd();
    }
   
    /**
     * Used to create a new DragLayer from XML.
     *
     * @param context The application's context.
     */

    public DragController(Context context) {
        mContext = context;
        mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

    }

    /**
     * Starts a drag.
     * It creates a bitmap of the view being dragged. That bitmap is what you see moving.
     * The actual view can be repositioned if that is what the onDrop handle chooses to do.
     *
     * @param v The view that is being dragged
     * @param source An object representing where the drag originated
     * @param dragInfo The data associated with the object that is being dragged
     * @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
     *        {@link #DRAG_ACTION_COPY}
     */

    public void startDrag(View v, DragSource source, Object dragInfo, int dragAction) {
        // Start dragging, but only if the source has something to drag.
        boolean doDrag = source.allowDrag ();
        if (!doDrag) return;

        mOriginator = v;

        Bitmap b = getViewBitmap(v);

        if (b == null) {
            // out of memory?
            return;
        }

        int[] loc = mCoordinatesTemp;
        v.getLocationOnScreen(loc);
        int screenX = loc[0];
        int screenY = loc[1];

        startDrag(b, screenX, screenY, 0, 0, b.getWidth(), b.getHeight(),
                source, dragInfo, dragAction);

        b.recycle();

        if (dragAction == DRAG_ACTION_MOVE) {
            v.setVisibility(View.GONE);
        }
    }

    /**
     * Starts a drag.
     *
     * @param b The bitmap to display as the drag image.  It will be re-scaled to the
     *          enlarged size.
     * @param screenX The x position on screen of the left-top of the bitmap.
     * @param screenY The y position on screen of the left-top of the bitmap.
     * @param textureLeft The left edge of the region inside b to use.
     * @param textureTop The top edge of the region inside b to use.
     * @param textureWidth The width of the region inside b to use.
     * @param textureHeight The height of the region inside b to use.
     * @param source An object representing where the drag originated
     * @param dragInfo The data associated with the object that is being dragged
     * @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
     *        {@link #DRAG_ACTION_COPY}
     */

    public void startDrag(Bitmap b, int screenX, int screenY,
            int textureLeft, int textureTop, int textureWidth, int textureHeight,
            DragSource source, Object dragInfo, int dragAction) {
        if (PROFILE_DRAWING_DURING_DRAG) {
            android.os.Debug.startMethodTracing("Launcher");
        }

        // Hide soft keyboard, if visible
        if (mInputMethodManager == null) {
            mInputMethodManager = (InputMethodManager)
                    mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        mInputMethodManager.hideSoftInputFromWindow(mWindowToken, 0);

        if (mListener != null) {
            mListener.onDragStart(source, dragInfo, dragAction);
        }

        int registrationX = ((int)mMotionDownX) - screenX;
        int registrationY = ((int)mMotionDownY) - screenY;

        mTouchOffsetX = mMotionDownX - screenX;
        mTouchOffsetY = mMotionDownY - screenY;

        mDragging = true;
        mDragSource = source;
        mDragInfo = dragInfo;

        mVibrator.vibrate(VIBRATE_DURATION);

        DragView dragView = mDragView = new DragView(mContext, b, registrationX, registrationY,
                textureLeft, textureTop, textureWidth, textureHeight);
        dragView.show(mWindowToken, (int)mMotionDownX, (int)mMotionDownY);
    }

    /**
     * Draw the view into a bitmap.
     */

    private Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);

        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);

        // Reset the drawing cache background color to fully transparent
        // for the duration of this operation
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);

        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
            return null;
        }

        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);

        return bitmap;
    }

    /**
     * Call this from a drag source view like this:
     *
     * <pre>
     *  @Override
     *  public boolean dispatchKeyEvent(KeyEvent event) {
     *      return mDragController.dispatchKeyEvent(this, event)
     *              || super.dispatchKeyEvent(event);
     * </pre>
     */

    public boolean dispatchKeyEvent(KeyEvent event) {
        return mDragging;
    }

    /**
     * Stop dragging without dropping.
     */

    public void cancelDrag() {
        endDrag();
    }

    private void endDrag() {
        if (mDragging) {
            mDragging = false;
            if (mOriginator != null) {
                mOriginator.setVisibility(View.VISIBLE);
            }
            if (mListener != null) {
                mListener.onDragEnd();
            }
            if (mDragView != null) {
                mDragView.remove();
                mDragView = null;
            }
        }
    }

    /**
     * Call this from a drag source view.
     */

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();

        if (action == MotionEvent.ACTION_DOWN) {
            recordScreenSize();
        }

        final int screenX = clamp((int)ev.getRawX(), 0, mDisplayMetrics.widthPixels);
        final int screenY = clamp((int)ev.getRawY(), 0, mDisplayMetrics.heightPixels);

        switch (action) {
            case MotionEvent.ACTION_MOVE:
                break;

            case MotionEvent.ACTION_DOWN:
                // Remember location of down touch
                mMotionDownX = screenX;
                mMotionDownY = screenY;
                mLastDropTarget = null;
                break;

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (mDragging) {
                    drop(screenX, screenY);
                }
                endDrag();
                break;
        }

        return mDragging;
    }

    /**
     * Sets the view that should handle move events.
     */

    void setMoveTarget(View view) {
        mMoveTarget = view;
    }    

    public boolean dispatchUnhandledMove(View focused, int direction) {
        return mMoveTarget != null && mMoveTarget.dispatchUnhandledMove(focused, direction);
    }

    /**
     * Call this from a drag source view.
     */

    public boolean onTouchEvent(MotionEvent ev) {
        if (!mDragging) {
            return false;
        }

        final int action = ev.getAction();
        final int screenX = clamp((int)ev.getRawX(), 0, mDisplayMetrics.widthPixels);
        final int screenY = clamp((int)ev.getRawY(), 0, mDisplayMetrics.heightPixels);

        switch (action) {
        case MotionEvent.ACTION_DOWN:
            // Remember where the motion event started
            mMotionDownX = screenX;
            mMotionDownY = screenY;
            break;
        case MotionEvent.ACTION_MOVE:
            // Update the drag view.  Don't use the clamped pos here so the dragging looks
            // like it goes off screen a little, intead of bumping up against the edge.
            mDragView.move((int)ev.getRawX(), (int)ev.getRawY());
            // Drop on someone?
            final int[] coordinates = mCoordinatesTemp;
            DropTarget dropTarget = findDropTarget(screenX, screenY, coordinates);
            if (dropTarget != null) {
                if (mLastDropTarget == dropTarget) {
                    dropTarget.onDragOver(mDragSource, coordinates[0], coordinates[1],
                        (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
                } else {
                    if (mLastDropTarget != null) {
                        mLastDropTarget.onDragExit(mDragSource, coordinates[0], coordinates[1],
                            (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
                    }
                    dropTarget.onDragEnter(mDragSource, coordinates[0], coordinates[1],
                        (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
                }
            } else {
                if (mLastDropTarget != null) {
                    mLastDropTarget.onDragExit(mDragSource, coordinates[0], coordinates[1],
                        (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
                }
            }
            mLastDropTarget = dropTarget;

            // The original Launcher activity supports a delete region and scrolling.
              // It is not needed in this example.
           
            // Scroll, maybe, but not if we're in the delete region.
           /* boolean inDeleteRegion = false;
            if (mDeleteRegion != null) {
                inDeleteRegion = mDeleteRegion.contains(screenX, screenY);
            }
            //Log.d(TAG, "inDeleteRegion=" + inDeleteRegion + " screenX=" + screenX
            //        + " mScrollZone=" + mScrollZone);
            if (!inDeleteRegion && screenX < mScrollZone) {
                if (mScrollState == SCROLL_OUTSIDE_ZONE) {
                    mScrollState = SCROLL_WAITING_IN_ZONE;
                    mScrollRunnable.setDirection(SCROLL_LEFT);
                    mHandler.postDelayed(mScrollRunnable, SCROLL_DELAY);
                }
            } else if (!inDeleteRegion && screenX > scrollView.getWidth() - mScrollZone) {
                if (mScrollState == SCROLL_OUTSIDE_ZONE) {
                    mScrollState = SCROLL_WAITING_IN_ZONE;
                    mScrollRunnable.setDirection(SCROLL_RIGHT);
                    mHandler.postDelayed(mScrollRunnable, SCROLL_DELAY);
                }
            } else {
                if (mScrollState == SCROLL_WAITING_IN_ZONE) {
                    mScrollState = SCROLL_OUTSIDE_ZONE;
                    mScrollRunnable.setDirection(SCROLL_RIGHT);
                    mHandler.removeCallbacks(mScrollRunnable);
                }
            }
            */

            break;
        case MotionEvent.ACTION_UP:
            if (mDragging) {
                drop(screenX, screenY);
            }
            endDrag();

            break;
        case MotionEvent.ACTION_CANCEL:
            cancelDrag();
        }
        return true;
    }

    private boolean drop(float x, float y) {

        final int[] coordinates = mCoordinatesTemp;
        DropTarget dropTarget = findDropTarget((int) x, (int) y, coordinates);

        if (dropTarget != null) {
            dropTarget.onDragExit(mDragSource, coordinates[0], coordinates[1],
                    (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
            if (dropTarget.acceptDrop(mDragSource, coordinates[0], coordinates[1],
                    (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo)) {
                dropTarget.onDrop(mDragSource, coordinates[0], coordinates[1],
                        (int) mTouchOffsetX, (int) mTouchOffsetY, mDragView, mDragInfo);
                mDragSource.onDropCompleted((View) dropTarget, true);
                return true;
            } else {
                mDragSource.onDropCompleted((View) dropTarget, false);
                return true;
            }
        }
        return false;
    }

    private DropTarget findDropTarget(int x, int y, int[] dropCoordinates) {
        final Rect r = mRectTemp;

        final ArrayList<DropTarget> dropTargets = mDropTargets;
        final int count = dropTargets.size();
        for (int i=count-1; i>=0; i--) {
            final DropTarget target = dropTargets.get(i);
            target.getHitRect(r);
            target.getLocationOnScreen(dropCoordinates);
            r.offset(dropCoordinates[0] - target.getLeft(), dropCoordinates[1] - target.getTop());
            if (r.contains(x, y)) {
                dropCoordinates[0] = x - dropCoordinates[0];
                dropCoordinates[1] = y - dropCoordinates[1];
                return target;
            }
        }
        return null;
    }

    /**
     * Get the screen size so we can clamp events to the screen size so even if
     * you drag off the edge of the screen, we find something.
     */

    private void recordScreenSize() {
        ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(mDisplayMetrics);
    }

    /**
     * Clamp val to be &gt;= min and &lt; max.
     */

    private static int clamp(int val, int min, int max) {
        if (val < min) {
            return min;
        } else if (val >= max) {
            return max - 1;
        } else {
            return val;
        }
    }

    public void setWindowToken(IBinder token) {
        mWindowToken = token;
    }

    /**
     * Sets the drag listener which will be notified when a drag starts or ends.
     */

    public void setDragListener(DragListener l) {
        mListener = l;
    }

    /**
     * Remove a previously installed drag listener.
     */

    public void removeDragListener(DragListener l) {
        mListener = null;
    }

    /**
     * Add a DropTarget to the list of potential places to receive drop events.
     */

    public void addDropTarget(DropTarget target) {
        mDropTargets.add(target);
    }

    /**
     * Don't send drop events to <em>target</em> any more.
     */

    public void removeDropTarget(DropTarget target) {
        mDropTargets.remove(target);
    }

    /**
     * Don't send drop events to <em>target</em> any more.
     */

    public void removeAllDropTargets () {
        mDropTargets = new ArrayList<DropTarget> ();
    }

}
Se le zampe del coniglio sono così fortunate, che fine ha fatto il coniglio?

Offline matttt

Re:Problema con cast di una View[Fragment]
« Risposta #7 il: 23 Agosto 2013, 17:23:29 CEST »
+1
Fai un po' di debugging con Eclipse (o quel che usi) :P
O con le funzioni di Log o piazzando break points per cercare di capire cosa è null e perché.
E' troppo faticoso farlo solo studiando pezzi di app di qualcun altro :P
Le mie apps su Google Play Store:

Offline MisterAnt

  • Utente normale
  • ***
  • Post: 272
  • Respect: +4
    • IlSikano
    • Mostra profilo
  • Dispositivo Android:
    Galaxy S4 Active,Galaxy SIII I9300, Galaxy Tab GT-P5100
  • Play Store ID:
    MisterAnt
  • Sistema operativo:
    Ubuntu 12.04/Winzoz 7/Winzoz xp
Re:Problema con cast di una View[Fragment]
« Risposta #8 il: 23 Agosto 2013, 17:27:37 CEST »
0
Ok, grazie mille per l'aiuto :)
+1
Se le zampe del coniglio sono così fortunate, che fine ha fatto il coniglio?