Center programmatically View inside another view that is inside GridLayout (that is inside RelativeLayout)

时间:2016-10-20 12:50:08

标签: android android-layout gridview android-view

I would like to center an ImageView to a Button (that is inside a GridLayout (that is inside a RelativeLayout that contains all)). I tried different option but none worked.

    ImageView image = new ImageView(getApplicationContext());
    image.setImageResource(R.drawable.heart);
    int lastSelectedID = currentIds.get(currentIds.size()-1);
    View lastButton = findViewById(lastSelectedID); //Is inside the GridLayout
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(100, 100);
//  lp.addRule(RelativeLayout.CENTER_IN_PARENT);                        
//  lp.addRule(RelativeLayout.CENTER_IN_PARENT, lastSelectedID);                        
//  lp.addRule(RelativeLayout.ABOVE, lastSelectedID);                       
    lp.addRule(RelativeLayout.ALIGN_LEFT, lastSelectedID);                      
    lp.addRule(RelativeLayout.ALIGN_RIGHT, lastSelectedID);                     
    image.setLayoutParams(lp);
    Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.spark);
    image.startAnimation(animation);
    final ViewGroup mainLayout = (ViewGroup) findViewById(R.id.layout_main); //relative layout that contains all
    mainLayout.addView(image);

I put the new ImageView inside the RelativeLayoute instead its inner GridLayout. This because the ImageView animation can move outside the GridLayout.

2 个答案:

答案 0 :(得分:0)

You can nest a linear layout in the relative layout and then use the myView.setX(myX) and myView.setY(myY) methods.

Hope I Helped :D

答案 1 :(得分:0)

I solved in this way:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(100, 100);
lp.addRule(RelativeLayout.ALIGN_LEFT, gridLayout.getId());
lp.addRule(RelativeLayout.ALIGN_TOP, gridLayout.getId());
lp.setMargins(lastButtonPositionX, lastButtonPositionY, 0, 0);