【问题标题】:Android Creating button dynamically and fill layoutAndroid动态创建按钮并填充布局
【发布时间】:2012-01-15 11:02:46
【问题描述】:

我正在动态创建一个按钮。按钮的数量取决于 arraylist 的大小。问题是,在创建按钮后,我将使用 addview 方法添加到布局中。问题是我使用的是线性布局,因为默认情况下线性布局的方向是水平的,所以按钮将水平填充布局。因此,某些按钮是不可见的。我想要实现的是看起来像这样的东西

我的代码如下:

Button[] tv = new Button[arraylist.size()];
for(int i=0;i<arraylist.size();i++){                                
    tv[i] = new Button(getApplicationContext());
    tv[i].setText(arraylist.get(i).toString());
    tv[i].setTextColor(Color.parseColor("#000000"));
    tv[i].setTextSize(20);
    tv[i].setPadding(15, 5, 15, 5);     
    linearlayout.addView(tv[i]);    
}

如果我将线性布局的方向设置为垂直,则按钮将垂直填充。因此,如果有任何解决方案可以动态创建按钮并填充水平和垂直布局,如图所示。

【问题讨论】:

    标签: android android-layout android-widget dynamically-generated


    【解决方案1】:

    SDK 中没有完全符合您的目标的固定布局(即水平布置尽可能多的子级,然后流到下一行以布置更多),因此您需要创建一个自定义ViewGroup 来实现此目的。幸运的是,Romain Guy 在 Devoxx 的一次演示中在屏幕上创建了一个现场直播。

    这是presentation video的链接。

    这是sample code and slides的链接。

    HTH

    【讨论】:

      【解决方案2】:

      经过 2 天的努力思考这个问题,我终于找到了解决方案。我尝试将我所有的联系人列表,将其存储在 arraylist 中并为每个元素创建按钮,我对显示在屏幕上的结果非常满意。这是我的诀窍。我非常感谢其他人的任何评论。

      变量声明;

      int currWidth;
      int currCounter;
      boolean isNewLine;
      LinkedList<HashMap<String,Object>> button;
      ArrayList<String> nameNumber = new ArrayList<String>();
      contactWrapper = (LinearLayout) findViewById(R.id.multiple_selection);
      

      创建按钮 onClick 事件;

      for(int i=0;i<nameNumber.size();i++){                               
                  tv[i] = new Button(getApplicationContext());                            
                  String[] namePhone = nameNumber.get(i).toString().split("@@");
                  phoneNumber.add(namePhone[1]);
                  tv[i].setText(namePhone[0]);
                  tv[i].setTag(namePhone[1]);
                  tv[i].setTextColor(Color.parseColor("#000000"));                                
                  tv[i].setTextSize(20);
                  tv[i].setPadding(15, 5, 15, 5);                                 
                  tv[i].measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                  HashMap<String, Object> map = new HashMap<String,Object>();
                  map.put("button", tv[i]);
                  map.put("width", tv[i].getMeasuredWidth());                             
                  button.add(map);
              }
              drawLayout();
      

      drawlayout 方法是我添加按钮并进行相应排列以适应布局的地方;

      public void drawLayout(){
              int counter=0;
              contactWrapper.setOrientation(LinearLayout.VERTICAL);
              currCounter=0;
              currWidth=0;
              isNewLine=false;
              LinearLayout[] row = new LinearLayout[nameNumber.size()];
              row[currCounter] = new LinearLayout(getApplicationContext());
              @SuppressWarnings("rawtypes")       
              Iterator it = button.iterator();
              for(int i = 0; i<button.size(); i++){   
                  it.next();  
                  row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                  currWidth += Integer.parseInt(button.get(i).get("width").toString());
                  if(isNewLine){              
                      if(currWidth < contactWrapper.getWidth()){  
                          row[currCounter].addView((View) button.get(i).get("button"));
                          if(!it.hasNext()){                      
                              contactWrapper.addView(row[currCounter]);
                          }else{                      
                              if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
                                  isNewLine=true;
                                  contactWrapper.addView(row[currCounter]);
                                  currCounter+=1; 
                                  row[currCounter] = new LinearLayout(getApplicationContext());
                                  currWidth=0;
                              }else{
                                  isNewLine=false;
                              }
                          }
                      }else{
                          isNewLine=true;
                          contactWrapper.addView(row[currCounter]);
                          currCounter+=1; 
                          row[currCounter] = new LinearLayout(getApplicationContext());
                          currWidth=0;
                      }                                               
                  }else{
                      if(currWidth < contactWrapper.getWidth()){                                      
                          if(!it.hasNext()){
                              row[currCounter].addView((View) button.get(i).get("button"));
                              contactWrapper.addView(row[currCounter]);
                          }else{
                              row[currCounter].addView((View) button.get(i).get("button"));
                              if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
                                  isNewLine=true;
                                  contactWrapper.addView(row[currCounter]);
                                  currCounter+=1; 
                                  row[currCounter] = new LinearLayout(getApplicationContext());
                                  currWidth=0;
                              }else{
                                  isNewLine=false;
                              }
                          }
                      }else{
                          isNewLine=true;
                          contactWrapper.addView(row[currCounter]);
                          currCounter+=1; 
                          row[currCounter] = new LinearLayout(getApplicationContext());
                          currWidth=0;
                      }
                  }           
                  counter++;
              }            
          }
      

      这段代码很乱 + 我没有充分利用数组的大小

      LinearLayout[] row = new LinearLayout[nameNumber.size()];
      

      但它对我有用。

      【讨论】:

      • 什么是“contactWrapper、multiple_selection、tv、phoneNumber、LayoutParams”??!!
      【解决方案3】:

      使用TableLayout 而不是LinearLayout 这是tutorial 希望这会帮助你理解这个想法

      【讨论】:

      • 感谢您的反馈。我之前尝试过,但它会拉伸按钮并每行显示一个按钮。就我而言,我想包装按钮的文本。所以每行按钮显示的数量取决于按钮的大小。
      【解决方案4】:

      你设置android:layout_width="fill_parent"了吗? 如果您不这样做,请执行此操作。

      【讨论】:

        【解决方案5】:

        好吧,您可以尝试使用更复杂的方法。您可以创建水平线性布局,并向其添加按钮。每次您尝试添加新按钮时,通过查找布局和按钮宽度之间的差异来检查是否有放置它的位置。

        每次水平布局被填满时,您将其添加到另一个垂直布局,并创建另一个水平布局来存储左侧按钮。

        我在我的应用程序中使用了这个技巧。

        【讨论】:

        • 是的......我也在考虑这个问题,不幸的是我只能获得线性布局的宽度。对于按钮宽度返回 0,因为 UI 尚未在屏幕上调整大小和布局,所以您能否提供示例代码来说明您对您的应用所做的操作。
        【解决方案6】:

        试试这个效果很好

        this.row = (LinearLayout)findViewById(R.id.tags); this.row.setOrientation(LinearLayout.VERTICAL); 线性布局一 = 新的线性布局(这个);

            //get the size of the screen
            Display display = getWindowManager().getDefaultDisplay();
            this.screenWidth = display.getWidth();  // deprecated
            this.screenHeight = display.getHeight();// depreceted
        
            for(int i=0; i<6; i++) {
        
                one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        
                this.button = new Button(this);
                button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                if(i==0) {
                    this.button.setText("Muhammad Aamir");
                } else if(i==1) {
                    this.button.setText("Ahsan");
                } else if(i==2) {
                    this.button.setText("Mujahid");
                } else if(i==3) {
                    this.button.setText("Waqas");
                } else if(i==4) {
                    this.button.setText("Ali");
                } else {
                    this.button.setText("Ahmer");
                }
        
                //get the size of the button text
                Paint mPaint = new Paint();
                mPaint.setAntiAlias(true);
                mPaint.setTextSize(button.getTextSize());
                mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
                float size = mPaint.measureText(button.getText().toString(), 0, button.getText().toString().length());
                size = size+14;
                this.totalTextWidth += size;
        
                if(totalTextWidth < screenWidth) {
                    one.addView(button);
                } else {
                    this.row.addView(one);
                    one = new LinearLayout(this);
                    one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                    one.addView(button);
                    this.totalTextWidth = size;
                }
            }
            this.row.addView(one);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-04-29
          • 2016-04-30
          • 1970-01-01
          • 1970-01-01
          • 2015-07-20
          • 2012-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多