如何从viewgroup onclicklistener获取具有id的子视图?

时间:2013-12-11 18:00:43

标签: android android-view viewgroup

我正在创建一个楼层地图,其中包含n个带增量值的动态按钮,并添加到自定义相对布局中。现在我需要为添加到视图的每个按钮创建onclicklistner。如何获取id或某些唯一值来标识单击哪个按钮。有人可以帮我这个,我在过去的10天里打破了我的头脑。提前谢谢。

这是我的自定义相对布局:

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

这是我创建楼层地图的片段类:

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

最后,我将交互式视图添加到相对布局中。

2 个答案:

答案 0 :(得分:0)

您可以为每个按钮使用setTag方法来设置ID。然后在onClick方法中,检索该值,并执行与该按钮相关的代码。

一些代码(未经测试):

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

答案 1 :(得分:0)

正如您在文档中所发现的那样,每个视图都可以拥有一个ID(使用setId (int id)或来自xml android:id)或标记(使用setTag (int key))并与之相关联您可以通过getId()getTag()获取该ID或代码。 现在,在您实际检索视图的任何ID之前,您必须通过编程或通过xml为该特定视图设置ID。 如果您没有为视图指定任何ID,并且您正在尝试获取该视图的ID,那么您将获得NO_ID。

  

根据文档:getId()返回此视图的标识符。如果视图没有ID,则用于标识视图的正整数或NO_ID。

现在,要解决您的问题,在向视图组添加按钮之前,请为该按钮分配唯一ID。 这里举一个例子来说明:

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