可能ですが、ボタンを同じレイアウトに含めるよりも複雑です。絶対にそうしたくない場合は、XML を使用できません (XML の方が常に高速です)。コードで 3 つの手順を実行する必要があります。
1.) ビューが描画されるまで待ちます
private void waitForViewToBeDrawn(){
// get your layout
final RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
ViewTreeObserver vto = mainLayout.getViewTreeObserver();
// add a listener
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
// you also want to remove that listener
mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// go on to next step
getPositionOfImageView();
}
});
}
このアプローチが私には最適ですが、問題がある場合は、いくつかの代替手段があります。API レベル 11 以降を使用する場合、[その他の解決策][2] もあります...
2.) imageView の最上位を取得する
private void getPositionOfImageView(){
ImageView imageView = (ImageView) findViewById(R.id.imageView);
// Top position view relative to parent (Button and ImageView have same parent)
int topCoordinate = imageView.getTop();
adjustButton(topCoordinate);
}
3.) 画像に合わせてボタンを追加または調整します
public void adjustButton(int topCoordinate){
Button button = (Button) findViewById(R.id.button);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = topCoordinate;
button.setLayoutParams(params);
}
API 11: button.setTop(topCoordinate)を使用すると、このステップがよりスムーズになります。
もちろん、すべてを短縮して単一の方法に入れることもできます.3つのステップで説明する方が良いと思いました. コードが開始に役立つことを願っています!