添加按钮到相对布局动态或扩展线性布局android

时间:2014-01-25 10:16:35

标签: android android-layout button

我想根据按钮和屏幕宽度动态地向相对布局添加按钮,如图所示。按钮数量不固定,按钮宽度取决于设置为按钮的文本。 enter image description here

我尝试使用以下代码实现此目的但是根据我的要求不能正常工作。 谁能帮帮我吗 ?请帮我解决这个问题。

RelativeLayout layout = (RelativeLayout) findViewById(R.id.genre_layout);
                    for(int i=0; i < genreList.size(); i++){

                        Button btn = new Button(MovieDetailsActivity.this);

                        btn.setText(genreList.get(i).getGenreName());
                        btn.setPadding(15, 5, 15, 5);
                        btn.setBackgroundColor(Color.parseColor("#FFFFFF"));
                        btn.setBackgroundColor(Color.parseColor("#80333333"));


                        LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        param.setMargins(5, 5, 5, 5);

                        if (i != 0){

                            int prevId = genreList.get(i).getGenreId();
                            param.addRule(RelativeLayout.RIGHT_OF, prevId);
                        }
                        btn.setLayoutParams(param);
                        btn.setId(genreList.get(i).getGenreId());

                        layout.addView(btn);

                    }

5 个答案:

答案 0 :(得分:0)

试试这个

Display display=getWindowManager().getDefaultDisplay();
    int width=display.getWidth();
    btn.setWidth(width);

或如果您有两个按钮,请执行

Display display=getWindowManager().getDefaultDisplay();
    int width=display.getWidth();
    btn1.setWidth(width/2);
    btn2.seTwidth(width/2);

<强>更新

LinearLayout.LayoutParams paramz = new LinearLayout.LayoutParams(
                             LayoutParams.MATCH_PARENT,
                             0dp, 1.0f);

然后btn.setLayoutParams(paramz);

答案 1 :(得分:0)

我建议您在问题中使用LinearLayout并提出Weight

LinearLayout

答案 2 :(得分:0)

我有代码将动态按钮添加到线性布局。只需查看它是否对您有所帮助https://docs.google.com/document/d/1QA1tAIe601fZT2Dlp1A0qDuLD0U4IqKL3f_Crx1rtkE/edit?usp=sharing

答案 3 :(得分:0)

尝试在relativelayout中添加动态按钮

 RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
 RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );


for (int i=0; i<4; i++) {
     Button btn = new Button(this);
     btn.setId(i);
     btn.setText("some_text");

    // lp.addRule(RelativeLayout.RIGHT_OF, <Id>);

     layout.addView(tv2, lp); 
}

答案 4 :(得分:0)

我通过使用FlowLayout解决了我的问题。 提供示例代码和参考资料here 它使用简单。谢谢大家的帮助。

相关问题