Viewコンポーネントを配置する際、マージンやパディングのような余白を指定したい場合は、ViewGroupのsetMargins()やViewのsetPadding()を使用します。
import android.app.Activity;
import android.widget.*;
public class MyClass extends Activity{
public void myMethod(){
int FP = LinearLayout.LayoutParams.FILL_PARENT;
int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
TextView text = new TextView(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WC,WC);
// マージンの設定 left:5px top:10px right:15px bottom:20px
params.setMargins(5,10,15,20);
// パディングの設定 left:5px top:10px right:15px bottom:20px
text.setPadding(5,10,15,20);
layout.addView(text,params);
}
}
xmlだとこうなります。
<?xml version="1.0" encoding="utf-8"?>
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5px"
android:layout_marginTop="10px"
android:layout_marginRight="15px"
android:layout_marginBottom="20px"
android:layout_margin="10px" // すべてに10px
android:paddingLeft="5px"
android:paddingTop="10px"
android:paddingRight="15px"
android:paddingBottom="20px"
android:padding="10px" // すべてに10px
/>
</LinearLayout>
参考: TextViewのカスタマイズ
参考: ImageViewのカスタマイズ
参考: Viewのクリックイベント
参考: Viewのタッチイベント


コメント