简体   繁体   English

addRule(RelativeLayout.BELOW,id)不起作用

[英]addRule(RelativeLayout.BELOW, id) doesn't work

I try to create 5 buttons below each other, but they appear on each other 我尝试在彼此下方创建5个按钮,但它们彼此显示

ArrayList<Button> btn = new ArrayList<>();
for (int i=0; i<10; i++) {
        Log.d("TEST", Integer.toString(i));

        btn.add(new Button(this));
        btn.get(i).setText(Integer.toString(i));
        if (i == 0) {

            btn.get(i).setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        } else {
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.BELOW, btn.get(i-1).getId());
            btn.get(i).setLayoutParams(lp);
        }
        ll.addView(btn.get(i)); 

What is wrong with my code? 我的代码有什么问题?

Solved by adding btn.get(i).setId(View.generateViewId()). 通过添加btn.get(i).setId(View.generateViewId())解决。 All id of buttons was -1 before using setId(). 使用setId()之前,按钮的所有ID均为-1。

From how you've named your layout, "ll", it seems you're adding those buttons to a LinearLayout. 从您将布局命名为“ ll”的方式来看,您似乎正在将这些按钮添加到LinearLayout中。 If that's the case, try changing that container layout to a RelativeLayout. 如果是这种情况,请尝试将该容器布局更改为RelativeLayout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 BaseAdapter 的 RelativeLayout addRule 不能很好地工作 - RelativeLayout addRule at BaseAdapter doesn't work very well 没有ID的RelativeLayout参数addRule - RelativeLayout Params addRule without ID Android Studio:为什么addRule()不能从RelativeLayout.LayoutParams中运行? - Android Studio: Why wouldn't addRule() work from RelativeLayout.LayoutParams? 使用MATCH_PARENT的RelativeLayout不起作用 - RelativeLayout with MATCH_PARENT doesn't work 当RelativeLayout进入ScrollView时,触摸移动TextView不能正常工作 - When RelativeLayout is into a ScrollView, moving TextView with touch doesn't work correctly TextView的Center Gravity在RelativeLayout中的xxhdpi上不起作用 - Center Gravity for TextView doesn't work on xxhdpi in RelativeLayout 刷机上设置的Java android RelativeLayout Listener不能与listView一起使用 - Java android RelativeLayout set on swipe Listener doesn't work with listView inside 具有DEFAULT ID的INSERT在PostgreSQL中不起作用 - INSERT with DEFAULT id doesn't work in PostgreSQL 为什么ViewPager不在RelativeLayout内滑动? - Why ViewPager doesn't swiping inside RelativeLayout? RelativeLayout 在 ConstraintLayout 中的位置不理想 - RelativeLayout doesn't locate well in ConstraintLayout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM