カテゴリー
Android Java

RelativeLayoutでViewをCenterに配置

public class MainActivity extends AppCompatActivity {

  BackgroundService bs;

  Button button1;
  Button button2;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RelativeLayout rootLayout = new RelativeLayout(this);
    setContentView(rootLayout);

    bs = BackgroundService.getInstance();

    button1 = new Button(this);
    button1.setText("Task1");
    int button1Id = View.generateViewId();
    button1.setId(button1Id);
    RelativeLayout.LayoutParams buttonLP1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    buttonLP1.addRule(RelativeLayout.CENTER_IN_PARENT);
    button1.setLayoutParams(buttonLP1);
    button1.setOnClickListener(new OnButtonClicked());

    rootLayout.addView(button1);

    button2 = new Button(this);
    button2.setText("Task2");
    RelativeLayout.LayoutParams buttonLP2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    buttonLP2.addRule(RelativeLayout.BELOW, button1Id);
    buttonLP2.addRule(RelativeLayout.CENTER_HORIZONTAL);
    buttonLP2.topMargin = 20;
    button2.setLayoutParams(buttonLP2);

    rootLayout.addView(button2);
  }

  private class OnButtonClicked implements View.OnClickListener {

    @Override
    public void onClick(View v) {
      bs.backgroundTask1();
    }
  }

  private class OnButton2Clicked implements View.OnClickListener {

    @Override
    public void onClick(View view) {
      bs.backgroundTask2();
    }
  }
}