カテゴリー
Android Java

RelativeLayoutを使ってCircle Viewを作る

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int screenHeight = Resources.getSystem().getDisplayMetrics().heightPixels;

    LinearLayout layout = new LinearLayout(this);
    layout.setGravity(Gravity.CENTER);
    setContentView(layout);

    RelativeLayout circleView = new RelativeLayout(this);
    GradientDrawable gd = new GradientDrawable();
    gd.setSize(screenHeight/3, screenHeight/3);
    gd.setColor(Color.WHITE);
    gd.setStroke(10, Color.GRAY);
    gd.setCornerRadius(screenHeight/3/2);
    circleView.setBackground(gd);
    layout.addView(circleView);

    TextView tvTop = new TextView(this);
    tvTop.setText("Top");
    tvTop.setTextSize(50);
    RelativeLayout.LayoutParams tvTopLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    tvTopLP.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    tvTopLP.addRule(RelativeLayout.CENTER_HORIZONTAL);
    tvTopLP.topMargin = screenHeight / 3 / 5;
    tvTop.setLayoutParams(tvTopLP);

    circleView.addView(tvTop);

    View divider = new View(this);
    divider.setBackgroundColor(Color.GRAY);
    RelativeLayout.LayoutParams dividerLP = new RelativeLayout.LayoutParams(screenHeight / 3 / 10 * 9, 3);
    dividerLP.addRule(RelativeLayout.CENTER_IN_PARENT);
    divider.setLayoutParams(dividerLP);

    circleView.addView(divider);

    TextView tvBottom = new TextView(this);
    tvBottom.setText("Bottom");
    tvBottom.setTextSize(50);
    RelativeLayout.LayoutParams tvBottomLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    tvBottomLP.addRule(RelativeLayout.ALIGN_PARENT_TOP); // when set to ALIGN_PARENT_TOP, the layout will break
    tvBottomLP.addRule(RelativeLayout.CENTER_HORIZONTAL);
    tvBottomLP.topMargin = screenHeight / 3 / 5 * 3;
    tvBottom.setLayoutParams(tvBottomLP);

    circleView.addView(tvBottom);

    getSupportActionBar().hide();
  }
}