レイアウトを コードだけで記述 することで例えば、ボタンの位置や大きさを自由に「動的」に変えることができます。
2024.1.1
Button
レイアウトは他にもありますが、LinearLayoutのケースで基本的な設定とダイナミックにボタンの位置を変更したり、またRelativeLayoutのケースでも確認してみたいと思います。
 
1. setContentView
2. LinearLayoutのケース
3. 簡単なサンプコード
4. ボタン位置を動的に変える
5. RelativeLayoutのケース
6. サンプル動画
setContentView
setContentView はその名の通り、スクリーン画面にViewを設定するメソッドです。設定されるViewはいくつかあるLayout形式の一つでまとめられたViewグループになります。
![[Android] ButtonをJavaコードだけで設定する 1x1.trans - [Android] ButtonをJavaコードだけで設定する](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
setContentViewのメソッドは引数の取り方でいくつかあります
- setContentView(int layoutResID)
- レイアウトXMLファイルのIDを指定
 
- setContentView(View view)
- 簡略形です。今回はこれを使います
 
- setContentView(View view, ViewGroup.LayoutParams params)
Ref: Android Developer
以下は1.の例で activity_main.xml を設定しています
 
| 1 | setContentView(R.layout.activity_main); | 
 
このactivity_main.xmlの設定は静的、staticなものでアプリ起動中に簡単に変更することはできません。レイアウトを動的、dynamicに変化させたい場合は上の2.を使います。
 
| 1 2 3 | LinearLayout layout = new LinearLayout(this); ... setContentView(layout); | 
LinearLayoutのケース
ButtonをタップするとTextViewの表示を変える 簡単な例 を レイアウトファイル xml で作成しました。これをコードで書くとこのようになります。Buttonのインスタンス生成は、
 
| 1 | Button button = new Button(this); | 
 
レイアウトファイルに記述していたLinieaLayout部分は
 
| 1 2 3 4 5 6 7 8 9 10 | LinearLayout layout = new LinearLayout(this); // orientationは垂直方向 layout.setOrientation(LinearLayout.VERTICAL); // Layoutの横・縦幅の指定 layout.setLayoutParams(new LinearLayout.LayoutParams(     LinearLayout.LayoutParams.MATCH_PARENT,     LinearLayout.LayoutParams.MATCH_PARENT)); setContentView(layout); | 
 
となりますが、レイアウトXMLファイルを使わないので、その他にButtonやTextViewのレイアウトも設定します。
 
クリックリスナーは変わりません
 
簡単なサンプルコード
まとめるとこのようになります。
MainActivity.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | //package com.example.testbuttoncode; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity {     private TextView textView;     private boolean flag = false;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         // レイアウトファイルは呼ばない         //setContentView(R.layout.activity_main);         // リニアレイアウトの設定         LinearLayout layout = new LinearLayout(this);         // orientationは垂直方向         layout.setOrientation(LinearLayout.VERTICAL);         // Layoutの横・縦幅の指定         layout.setLayoutParams(new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT,                 LinearLayout.LayoutParams.MATCH_PARENT));         setContentView(layout);         // テキスト設定         textView = new TextView(this);         textView.setText(R.string.hello);         LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         textView.setLayoutParams(textLayoutParams);         layout.addView(textView);         // ボタンの設定         Button button = new Button(this);         button.setText(R.string.button);         LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         button.setLayoutParams(buttonLayoutParams);         layout.addView(button);         // リスナーをボタンに登録         // lambda式         button.setOnClickListener( v-> {             // flagがtrueの時             if (flag) {                 textView.setText(R.string.hello);                 flag = false;             }             // flagがfalseの時             else {                 textView.setText(R.string.world);                 flag = true;             }         });     } } | 
 
リソースファイルは必要です。
res\values\strings.xml
| 1 2 3 4 5 6 | <resources>     <string name="app_name">YourAppName</string>     <string name="hello">Hello</string>     <string name="world">World</string>     <string name="button">Button</string> </resources> | 
 
![[Android] ButtonをJavaコードだけで設定する 1x1.trans - [Android] ButtonをJavaコードだけで設定する](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
相変わらずレイアウトが…ですが以降で味付けしてみます。
ボタン位置を動的に変える
基本的なコードから、中央寄せ、テキストサイズの変更などを加えます。
 
MainActivity.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | //package com.example.testbuttoncode2; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.util.TypedValue; import android.view.Gravity; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity {     private TextView textView;     private boolean flag = false;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         // リニアレイアウトの設定         LinearLayout layout = new LinearLayout(this);         layout.setOrientation(LinearLayout.VERTICAL);         layout.setLayoutParams(new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT,                 LinearLayout.LayoutParams.MATCH_PARENT));         // レイアウト中央寄せ         layout.setGravity(Gravity.CENTER);         setContentView(layout);         // テキスト設定         textView = new TextView(this);         textView.setText(R.string.hello);         // テキストサイズ 30sp         textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);         // テキストカラー         textView.setTextColor(Color.rgb(0x0, 0x0, 0x0));         LinearLayout.LayoutParams textLayoutParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         textView.setLayoutParams(textLayoutParams);         layout.addView(textView);         // ボタンの設定         Button button = new Button(this);         button.setText(R.string.button);         // dp単位を取得         float scale = getResources().getDisplayMetrics().density;         int buttonWidth = (int)(150 * scale);         // 横幅 150dp, 縦 100dp に設定         LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(                 buttonWidth, LinearLayout.LayoutParams.WRAP_CONTENT);         // マージン 20dp に設定         int margins = (int)(20 * scale);         buttonLayoutParams.setMargins(margins, margins, margins, margins);         button.setLayoutParams(buttonLayoutParams);         layout.addView(button);         // リスナーをボタンに登録         button.setOnClickListener(v -> {                 // flagがtrueの時                 if (flag) {                     textView.setText(R.string.hello);                     flag = false;                 }                 // flagがfalseの時                 else {                     textView.setText(R.string.world);                     flag = true;                 }         });     } } | 
 
リソースは同じです。
![[Android] ButtonをJavaコードだけで設定する 1x1.trans - [Android] ButtonをJavaコードだけで設定する](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif)
Dynamicにボタンを変更:
これだけだとあまりありがたみが無いですが、画面サイズに応じて動的に位置や大きさを変化させてみます。
MainActivity.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | //package com.example.testbuttoncode3; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.util.TypedValue; import android.view.Gravity; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity {     private TextView textView;     private boolean flag = false;     private Button button;     private LinearLayout.LayoutParams buttonLayoutParams;     private float scale;     private int buttonWidth;     private int margins;     int mParent = LinearLayout.LayoutParams.MATCH_PARENT;     int wContent = LinearLayout.LayoutParams.WRAP_CONTENT;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         // リニアレイアウトの設定         LinearLayout layout = new LinearLayout(this);         layout.setOrientation(LinearLayout.VERTICAL);         layout.setLayoutParams(new LinearLayout.LayoutParams(                 mParent, mParent));         // レイアウト中央寄せ         layout.setGravity(Gravity.CENTER);         setContentView(layout);         // テキスト設定         textView = new TextView(this);         textView.setText(R.string.hello);         // テキストサイズ 30sp         textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);         // テキストカラー         textView.setTextColor(Color.rgb(0x0, 0x0, 0x0));         LinearLayout.LayoutParams textLayoutParams =                 new LinearLayout.LayoutParams(wContent, wContent);         textView.setLayoutParams(textLayoutParams);         layout.addView(textView);         // ボタンの設定         button = new Button(this);         button.setText(R.string.button);         // dp単位を取得         scale = getResources().getDisplayMetrics().density;         // マージン 20dp に設定         margins = (int)(20 * scale);         buttonWidth = (int)(150 * scale);         // 横幅 150dp に設定         buttonLayoutParams = new LinearLayout.LayoutParams(                 buttonWidth, wContent);         // setMargins (int left, int top, int right, int bottom)         buttonLayoutParams.setMargins(margins, margins, margins, margins);         button.setLayoutParams(buttonLayoutParams);         layout.addView(button);         // リスナーをボタンに登録         button.setOnClickListener( v -> {                 // flagがtrueの時                 if (flag) {                     textView.setText(R.string.hello);                     mode1();                     flag = false;                 }                 // flagがfalseの時                 else {                     textView.setText(R.string.world);                     mode2();                     flag = true;                 }         });     }     private void mode1(){         buttonWidth = (int)(150 * scale);         // 横幅 150dp に設定         buttonLayoutParams = new LinearLayout.LayoutParams(                 buttonWidth, wContent);         buttonLayoutParams.setMargins(margins, margins, margins, margins);         button.setLayoutParams(buttonLayoutParams);     }     private void mode2(){         buttonWidth = (int)(250 * scale);         int buttonHeight = (int)(100 * scale);         // 横幅 250dp に設定         buttonLayoutParams = new LinearLayout.LayoutParams(                 buttonWidth, buttonHeight);         buttonLayoutParams.setMargins((int) (5 * scale), (int)(50 * scale),                 (int)(50 * scale), (int)(20 * scale));         button.setLayoutParams(buttonLayoutParams);     } } | 
![[Android] ButtonをJavaコードだけで設定する 1x1.trans - [Android] ButtonをJavaコードだけで設定する](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif) 
![[Android] ButtonをJavaコードだけで設定する 1x1.trans - [Android] ButtonをJavaコードだけで設定する](https://akira-watson.com/wp-content/themes/simplicity2/images/1x1.trans.gif) 
 
ボタンの横幅を250dp,縦幅を100dp
マージンを 左5dp,上50dp, 右50dp に変えてみました
dpについてはdp, px, dpi, sp アプリ画面の解像度単位を包括・統一的に扱うを参照してください
テキストの色を変えたり
テキストサイズを変えたりなどは
xmlと絡めて簡単にできますが
位置の調整はこのようにする必要があります
Buttonのタップを匿名クラスで取得していますが、他にもいくつも方法があります。
onClickListenerの色々な設定
RelativeLayoutのケース
LinearLayoutと基本的には同じですが、RelativeLayoutとしての位置指定が必要です。
+αで多少アレンジしてみました。
 
MainActivity.java
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | //package your.package.name; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.util.TypedValue; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity {     private RelativeLayout.LayoutParams buttonLayoutParams;     private TextView textView;     private Button button;     private int buttonWidth, buttonHeight;     private float scale;     private boolean flag = false;     int mParent = RelativeLayout.LayoutParams.MATCH_PARENT;     int wContent = RelativeLayout.LayoutParams.WRAP_CONTENT;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         // リラティブレイアウトの設定         RelativeLayout layout = new RelativeLayout(this);         layout.setLayoutParams(new RelativeLayout.LayoutParams(                 mParent, mParent));         // 背景色の設定         layout.setBackgroundColor(Color.rgb(220,255,240));         setContentView(layout);         // dp 設定         scale = getResources().getDisplayMetrics().density;         // テキスト設定         textView = new TextView(this);         textView.setText(R.string.hello);         // テキストサイズ 30sp         textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);         // テキストカラー         textView.setTextColor(Color.rgb(0x0, 0x0, 0xff));         RelativeLayout.LayoutParams textLayoutParams =                 new RelativeLayout.LayoutParams(wContent, wContent);         // setMargins (int left, int top, int right, int bottom)         textLayoutParams.setMargins((int)(150*scale), (int)(300*scale), 0, 0);         textView.setLayoutParams(textLayoutParams);         layout.addView(textView);         // ボタンの設定         button = new Button(this);         button.setText(R.string.button);         button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);         // ボタンサイズ         buttonWidth = (int)(200 * scale);         buttonHeight = (int)(100 * scale);         buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);         // button margin : left, top, right, bottom         buttonLayoutParams.setMargins((int)(105*scale), (int)(360*scale), 0, 0);         button.setLayoutParams(buttonLayoutParams);         layout.addView(button);         // リスナーをボタンに登録         button.setOnClickListener( v -> {                 // flagがtrueの時                 if (flag) {                     textView.setText(R.string.hello);                     mode1();                     flag = false;                 }                 // flagがfalseの時                 else {                     textView.setText(R.string.world);                     mode2();                     flag = true;                 }         });     }     private void mode1(){         buttonWidth = (int)(250 * scale);         buttonHeight = (int)(100 * scale);         buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);         // setMargins (int left, int top, int right, int bottom)         buttonLayoutParams.setMargins((int)(150*scale), (int)(360*scale), 0, 0);         button.setLayoutParams(buttonLayoutParams);     }     private void mode2(){         buttonWidth = (int)(270 * scale);         buttonHeight = (int)(200 * scale);         buttonLayoutParams = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);         // setMargins (int left, int top, int right, int bottom)         buttonLayoutParams.setMargins((int) (5 * scale), (int)(100 * scale),                 (int)(50 * scale), (int)(20 * scale));         button.setLayoutParams(buttonLayoutParams);     } } | 
サンプル動画
関連ページ:
- 簡単な Button アプリを作る
- ButtonをJavaコードだけで設定する
- カスタムボタンを作る
- ImageButton:Button, ImageButton に画像を設定する
- onClickListenerの色々な設定
- Button 配列を設定する
References:
setContentView
LinearLayout
RelativeLayout
