我添加兩個按鈕到UI,但它們在界面上是上下顯示的。我想實現的是它們左右顯示。我用的這段代碼還缺什麼啊?請大家幫我檢查下,謝謝。
m_btnCrown = new ImageButton(this);
m_btnCrown.setImageResource(R.drawable.king_crown_thumb);
m_btnCrown.setAlpha(100);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
addContentView(m_btnCrown, lp);
m_btnMonkey = new ImageButton(this);
m_btnMonkey.setImageResource(R.drawable.monkey_small);
m_btnMonkey.setAlpha(100);
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.addRule(RelativeLayout.RIGHT_OF, m_btnCrown.getId());
addContentView(m_btnMonkey, lp);
我寫了一個簡單的例子來演示如何以編程方式創建一個布局:
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 創建一個新的RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// 定義RelativeLayout布局屬性
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// 創建一個新的TextView
TextView tv = new TextView(this);
tv.setText("Test");
// 定義TextView裡的布局屬性
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
//設置 TextView的屬性
tv.setLayoutParams(lp);
relativeLayout.addView(tv);
setContentView(relativeLayout, rlp);
}
}