Kar*_*gan 65 android android-relativelayout
我在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);
Run Code Online (Sandbox Code Playgroud)
Oct*_*ean 139
我编写了一个快速示例来演示如何以编程方式创建布局.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
Run Code Online (Sandbox Code Playgroud)
理论上,一切都应该清楚,因为它被评论.如果你不明白的话就告诉我.
Kar*_*gan 22
在如何以编程方式在RelativeLayout中布局视图中找到答案?
我们应该使用setId()显式设置id.只有这样,RIGHT_OF规则才有意义.
我做的另一个错误是,重用控件之间的layoutparams对象.我们应该为每个控件创建新对象
| 归档时间: |
|
| 查看次数: |
111785 次 |
| 最近记录: |