简体   繁体   中英

How to get child view with id from a viewgroup onclicklistener?

I am creating a floor map with n number of dynamic buttons with incremental value and added to a custom relative layout. Now i need to create onclicklistner for each buttons added to a view. How to get the id or some unique value to identify which button is clicked. Can somebody please help me on this i am breaking my head for the past 10 days. Thanks in advance.

This is my Custom Relative layout :

public class InteractiveView extends RelativeLayout implements OnClickListener{
    Matrix matrix = new Matrix();
    private float mPositionX = 0;
    private float mPositionY = 0;
    private float mScale = 0.1f;
    private Context context;

    private boolean canvasFlag = true;

    public InteractiveView(Context context) {
        super(context);
        this.context = context;
        this.setWillNotDraw(false);
//      this.setOnTouchListener(mTouchListener);
        this.setOnClickListener(this);
    }   

    public void setPosition(float lPositionX, float lPositionY){
        mPositionX = lPositionX;
        mPositionY = lPositionY;
    }

    public void setMovingPosition(float lPositionX, float lPositionY){
        mPositionX += lPositionX;
        mPositionY += lPositionY;
    }

    public void setScale(float lScale){ 
        mScale = lScale;
    }

    protected void dispatchDraw(Canvas canvas) {        
        canvas.save();  
        //      canvas.setMatrix(matrix);
        Log.e("Canvas Height ",canvas.getWidth()+" "+canvas.getHeight());
        Log.e("Canvas Height ",getWidth() /14 +" "+getHeight()/12 );
        Log.e("Canvas Density "," "+canvas.getDensity() );
        canvas.translate(mPositionX*mScale, mPositionY*mScale);     
        canvas.translate(getWidth() / 14,getHeight() / 12);  


        if (mScale < 0.10)
            mScale = 0.1f;
        canvas.scale(mScale, mScale);
        Log.e("Scale :  ",mScale+" ");
        super.dispatchDraw(canvas);
        canvas.restore();
    }   

    // touch events
    private final int NONE = 0;
    private final int DRAG = 1;
    private final int ZOOM = 2;
    private final int CLICK = 3;

    // pinch to zoom
    private float mOldDist;
    private float mNewDist;
    private float mScaleFactor = 0.01f;

    // position
    private float mPreviousX;
    private float mPreviousY;

    int mode = NONE;

    @SuppressWarnings("deprecation")
    public OnTouchListener mTouchListener = new  OnTouchListener(){
        public boolean onTouch(View v, MotionEvent e) {

            /*Button button = (Button)v;
            Log.e("Button Text : "," "+button.getText().toString());
            */

            float x = e.getX();
            float y = e.getY();
            switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN: // one touch: drag            
                mode = CLICK;
                break;
            case MotionEvent.ACTION_POINTER_2_DOWN: // two touches: zoom            
                mOldDist = spacing(e);          
                mode = ZOOM; // zoom
                break;
            case MotionEvent.ACTION_UP: // no mode          
                mode = NONE;
                break;
            case MotionEvent.ACTION_POINTER_2_UP: // no mode
                mode = NONE;            
                break;
            case MotionEvent.ACTION_MOVE: // rotation

                if (e.getPointerCount() > 1 && mode == ZOOM) {
                    /*mNewDist = spacing(e) - mOldDist;   

                    mScale += mNewDist*mScaleFactor;
                    invalidate();

                    mOldDist = spacing(e);  */

                } else if (mode == CLICK || mode == DRAG) {
                    float dx = (x - mPreviousX)/mScale;
                    float dy = (y - mPreviousY)/mScale;

                    setMovingPosition(dx, dy);
                    invalidate();
                    mode = DRAG;                        
                }
                break;
            }
            mPreviousX = x;
            mPreviousY = y;
            return true;
        }
    };

    // finds spacing
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y)/4;
    }

This is my fragment class where i create floor map :

public class FloorMapFragment extends Fragment implements OnClickListener {

    ViewGroup root;
    Button exhibitor;
    ZoomControls zoom;
    int id = 0;
    float dx=0,dy=0,x=0,y=0;
    InteractiveView mInteractiveView;
    int startX, startY;
    boolean isClicked = false;
    int unit = 100;
    int incremental = 100;
    int new_X;
    int i;
    int new_Width = new_X + incremental;
    int new_Y;
    int new_Hight = new_Y + incremental;

    int leftMargin, topMargin;
    int orange = Color.parseColor("#C0680F");
    int maroon = Color.parseColor("#5F0C0C");
    int pink = Color.parseColor("#F45C91");
    int moov = Color.parseColor("#6E4689");
    int gray = Color.parseColor("#777777");
    int red = Color.parseColor("#E31E26");
    int blue = Color.parseColor("#3A53A4");
    int green = Color.parseColor("#70BD59");
    int cyan = Color.parseColor("#70CDDD");
    RelativeLayout r;

    //  View mainView = null;

    // Remember some things for zooming
    PointF start = new PointF();
    PointF mid = new PointF();

    float oldDist = 1f;
    PointF oldDistPoint = new PointF();

    public static String TAG = "ZOOM";
    int mScreenWidth = 0;
    int mScreenHeight= 0;


    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    enum Direction {
        LEFT, RIGHT, UP, DOWN
    };

    FloorListner listner;

    @SuppressWarnings("deprecation")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        root = (ViewGroup) inflater.inflate(R.layout.floor_main, null);
        //      mainView = (RelativeLayout)root.findViewById(R.id.zoom_layout);
        r = (RelativeLayout) root.findViewById(R.id.my_relative_layout);
        zoom = (ZoomControls)root. findViewById(R.id.zoomControls1);

        mScreenWidth = r.getWidth();


        /*MainActivity.activity.getResources()
                .getDisplayMetrics().widthPixels;*/
        mScreenHeight = r.getHeight();

        /*MainActivity.activity.getResources()
                .getDisplayMetrics().heightPixels; */


        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);
        layoutParams.height = 75;
        layoutParams.width = 57;

//      layoutParams.bottomMargin = 100;
//      layoutParams.setMargins(0, 0, 0, 100);
        //      layoutParams.setMargins(-220, 0, 0, 0);
        /*ImageView lImageView = new ImageView(MainActivity.activity);
        lImageView.setLayoutParams(new RelativeLayout.LayoutParams(-1,-1));
        lImageView.setImageResource(R.drawable.transparentimage);;*/

        mInteractiveView = new InteractiveView(MainActivity.activity);

        //      mInteractiveView.setOnClickListener(this);
        //      mInteractiveView.setOnTouchListener(mTouchListener);
        //      mInteractiveView.setLayoutParams(new RelativeLayout.LayoutParams(-5,-5 ));
        //      mInteractiveView.setLayoutParams(layoutParams);
        //      mInteractiveView.setPosition(-mScreenWidth/2, -mScreenHeight/2);


        zoom.setOnZoomInClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                float x = r.getScaleX();
                float y = r.getScaleY();

                Log.e("Zoon In Listener : ", "X Scale : "+ x );
                Log.e("Zoon In Listener : ", "Y Scale : "+ y );

                Log.e("Zoon In Width  : ", "X Scale : "+ r.getWidth() );
                Log.e("Zoon In Height  : ", "Y Scale : "+ r.getHeight() );

                if (x <= 6.0 && y <= 6.0){
                    r.setScaleX((float) (x + 0.5));
                    r.setScaleY((float) (y + 0.5));
                }
            }
        });

        zoom.setOnZoomOutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                float x = r.getScaleX();
                float y = r.getScaleY();

                Log.e("Zoon Out Listener : ", "X Scale : "+ x );
                Log.e("Zoon Out Listener : ", "Y Scale : "+ y );


                if (x > 1.0 && y > 1.0){
                    r.setScaleX((float) (x - 0.5));
                    r.setScaleY((float) (y - 0.5));
                }
            }
        });



        ProgressDialog d = new ProgressDialog(getActivity());
        d.setMessage("Loading Map");
        d.show();
        draw();
        d.dismiss();
        /*
        mInteractiveView.setOnClickListener(new OnClickListener() {

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

            }
        });*/

        /*for( i=0; i<((ViewGroup)mInteractiveView).getChildCount(); ++i) {
            View nextChild = ((ViewGroup)mInteractiveView).getChildAt(i);
            try {
                final Button b = (Button) nextChild;

                Log.e("Button Text : ", " : "+b.getText().toString());
                b.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int index = ((ViewGroup)b.getParent()).indexOfChild(b);
                        Log.e("Button get Id : ", ""+v.getTag().toString());


                    }
                });
            } catch (Exception e) {
            }
        }*/
        //      
        //      mInteractiveView.addView(lImageView);
        //      r.setLayoutParams(layoutParams);
        r.addView(mInteractiveView);


        /*  ExhibitorDAO dao = new ExhibitorDAO(getActivity());
        workAround(dao, "K19");*/

        /*  Fragment fragment = new NewsFragment();
        FragmentTransaction trans =  ;
        trans.addToBackStack(null);
        trans.replace(R.id.main, fragment);
        trans.commit();*/

        //      r.setOnTouchListener(MyOnTouchListener);
//      r.setLayoutParams(layoutParams);

        Log.e("Width And Height : ", "Width : "+r.getLayoutParams().width+ " : Height :"+r.getLayoutParams().height);
        return root;
    }

    private OnTouchListener mTouchListener = new  OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                isClicked = true;
                x = event.getX();
                y = event.getY();
                dx = x-r.getX();
                dy = y-r.getY();
                break;
            case MotionEvent.ACTION_UP:
                if (isClicked){
                    isClicked = false;
                    /*Button b = (Button) v;
                    ExhibitorDAO dao = new ExhibitorDAO(getActivity());
                    workAround(dao,b.getText().toString());*/
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:
                isClicked = false;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                isClicked = false;
                break;
            case MotionEvent.ACTION_MOVE:
                r.setX(event.getX()-dx);
                r.setY(event.getY()-dy);

                isClicked = false;
                break;

            default:
                break;
            }
            return false;
        }

    };



    private void decreaseXBy(int i) {
        new_X = new_X - (2 * i);
    }

    private void reset() {
        new_X = 0;
        new_Y += incremental;
        ;
    }

    private void drawingH(Direction direction, float width) {
        if (direction == direction.RIGHT) {// means go to right direction{
            new_X += (incremental * width);
        } else if (direction == direction.LEFT) { // means go to left
            new_X -= (incremental * width);
        }

    }

    @Override
    public void onClick(View v) {

        // TODO Auto-generated method stub

        Button b = (Button) v;
        ExhibitorDAO dao = new ExhibitorDAO(getActivity());

        try{
            Exhibitor exhibitor = new Exhibitor();
            Log.e("Button Text : ", " : "+b.getText());
            if (!b.getText().equals("")) {
                Logger.log("floor:");
                exhibitor = dao.getExhibitorByBooth(b.getText().toString());
                ExhibitorApplication ex = new ExhibitorApplication();
                ex.exhibitor = exhibitor;

                if (exhibitor != null){
                    listner.Onfloorclick();
                    ex.fav_exhibitor  = 4 ; 
                    Logger.log("floor:"+ex.exhibitor.Exhibitor_FileNumber);
                }
                else
                {
                    Logger.log("floor:"+ex.exhibitor.Exhibitor_FileNumber);
                }

            }
            {
                Logger.log("floor:no data");
            }
        }
        catch(Exception ex)
        {
            Toast.makeText(getActivity(), "No Information "+ex.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    public Button drawExhibitor(float width, int height, int color,
            String label, String fileNumber, Direction d) {

        exhibitor = new Button(getActivity());


        //      exhibitor.setOnClickListener(this);
        //      exhibitor.setOnTouchListener(MyOnTouchListener);
        if (color == Color.BLUE)
            exhibitor.setBackgroundColor(Color.parseColor("#56A5EC"));
        if (color == Color.WHITE)
            exhibitor.setAlpha(0);
        else
            exhibitor.setBackgroundColor(color);

//      exhibitor.setId(id);
//      id++;
        exhibitor.setText(label);
        exhibitor.setTextSize(8);
        //      exhibitor.setId(foo);
        exhibitor.setTag(label);
        exhibitor.setTypeface(Typeface.DEFAULT_BOLD);
        exhibitor.setGravity(Gravity.CENTER);
        exhibitor.setTextColor(Color.WHITE);
        /*exhibitor.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e("Button get Id : ", ""+exhibitor.getId());

            }
        });*/
        exhibitor.setOnTouchListener(mTouchListener);

        leftMargin = new_X;
        topMargin = new_Y;
        drawingH(d, width);
        InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
                (int) (width * incremental), height * incremental);


        params.leftMargin = leftMargin;
        params.topMargin = topMargin;
        mInteractiveView.addView(exhibitor, params);
        params = null;
        if (color != Color.WHITE) {
            drawingHSpace();
        }

        return exhibitor;
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof FloorListner) {
            listner = (FloorListner) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet MyListFragment.OnItemSelectedListener");
        }
    }

    private void drawingHSpace() {
        new_X += 2;
    }

    private void drawingHSpace(float t) {
        new_X = (int) (new_X + (2 * t));
    }

    private void drawingVSpace() {
        new_Y += 2;
    }

    private void removeDrawingVSpace() {
        new_Y -= 2;
    }

    private void decreaseXBy(float i) {
        new_X = (int) (new_X - (2 * i));
    }


    private void drawLabel(float width, int height, int color, int drawable, Direction d) {
        // TODO Auto-generated method stub
        TextView image = new TextView(getActivity());
        //image.setText(label);
        image.setBackgroundResource(drawable);
        image.setGravity(Gravity.CENTER);
        image.setTextSize(20);
        image.setTypeface(Typeface.DEFAULT_BOLD);
        //image.setTextColor(color);
        //      image.setOnTouchListener(MyOnTouchListener);
        leftMargin = new_X;
        topMargin = new_Y;
        drawingH(d,width);
        InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
                (int)(width * incremental), height * incremental);
        params.leftMargin = leftMargin;
        params.topMargin = topMargin;
        mInteractiveView.addView(image, params);
    }
    private void drawLabel(float width, int height, int color, String label, Direction d) {
        // TODO Auto-generated method stub
        TextView image = new TextView(getActivity());
        image.setText(label);
        image.setGravity(Gravity.CENTER);
        image.setTextSize(20);
        image.setTypeface(Typeface.DEFAULT_BOLD);
        image.setTextColor(color);
        //      image.setOnTouchListener(mTouchListener);

        leftMargin = new_X;
        topMargin = new_Y;
        drawingH(d,width);
        InteractiveView.LayoutParams params = new InteractiveView.LayoutParams(
                (int)(width * incremental), height * incremental);
        params.leftMargin = leftMargin;
        params.topMargin = topMargin;
        mInteractiveView.addView(image, params);
    }


    private void draw() {
        drawExhibitor(28.5F, 3, Color.WHITE, "", "",  Direction.RIGHT);
        drawLabel(2, 3, blue, R.drawable.al_mamzar, Direction.RIGHT);
        reset();
        reset();

        drawExhibitor(16.5F, 1, Color.WHITE, "", "", Direction.RIGHT);
        drawLabel(2, 1, blue, R.drawable.business_center,  Direction.RIGHT);
        drawExhibitor(4.65F, 1, Color.WHITE, "", "",  Direction.RIGHT);
        drawLabel(1, 1, blue, R.drawable.bath_f,  Direction.RIGHT);
        drawExhibitor(14F, 1, Color.WHITE, "", "", Direction.RIGHT);
        drawLabel(1, 1, blue, R.drawable.bath_m,  Direction.RIGHT);
        //reset();
        reset();
        drawingVSpace();
        drawingVSpace();
           }
   }

Finally i am adding the Interactive View to a relative layout.

You can use the setTag method for each button, to set an id. Then in the onClick method, retrieve that value, and execute the code related to that button.

Some code (not tested):

private OnClickListener listener = new OnClickListener()
{           
    @Override
    public void onClick(View v) 
    {
        int id = (Integer)v.getTag();

        switch (id)
        {
            case 1: break;
            ....
        }
    }
});

for (int i=0 ; i<N ; i++)
{
    yourbutton.setTag(Integer.valueOf(i));
    yourbutton.setOnClickListener(listener);
}

As you will find it in the documentation that each view can have an id (using setId (int id) or from xml android:id ) or tag(using setTag (int key) ) associated with it and later on you can get that id or tag via getId() or getTag() . Now before you actually retrieve any id for a view at first you have to set an id for that specific view either via programmatically or via xml. If you don't specify any id for a view and you are trying get that view's id you will get NO_ID.

As per documentation: getId () returns this view's identifier.A positive integer used to identify the view or NO_ID if the view has no ID.

Now to address your problem, before you add a button to your viewgroup assign a unique id to that button. To illustrate more here is an example:

public class MainActivity extends Activity {
private LinearLayout mRootLayout;
private OnClickListener mOnClickListener = new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Log.e("mButton "," onClick");
        Toast.makeText(MainActivity.this, " "+arg0.getId(), Toast.LENGTH_LONG).show();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    mRootLayout = (LinearLayout)findViewById(R.id.mRootLayout);
    for(int i = 0;i<10;i++){
        Button mButton = new Button(this);
        mButton.setText("Button "+i);
        mButton.setId(i);           
        if(i<9){
            mButton.setOnClickListener(mOnClickListener);   
        }
        mRootLayout.addView(mButton);
    }
    Button testFindButton = (Button)mRootLayout.findViewById(9);
    testFindButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.e("testFindButton "," onClick");
            Toast.makeText(MainActivity.this, " testFindButton "+v.getId(), Toast.LENGTH_LONG).show();
        }
    });
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM