【问题标题】:How to add a button dynamically in Android?如何在Android中动态添加按钮?
【发布时间】:2009-12-05 08:57:03
【问题描述】:

如何在Android中动态添加按钮?

【问题讨论】:

    标签: android


    【解决方案1】:
    Button myButton = new Button(this);
    myButton.setText("Push Me");
    
    LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
    LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    ll.addView(myButton, lp);
    

    看看this的例子

    【讨论】:

    • 我更新了网址,因为旧网址给出了 404。请检查我是否引用了正确的页面。
    • 您能否完全符合LayoutParams 的要求?我看到超过 12 个具有此名称的类。
    • @Saeed 在这个具体的例子中,它是属于 LinearLayout 的 LayoutParams。 android.widget.LinearLayout.LayoutParams
    【解决方案2】:

    试试这个:

    for (int i = 1; i <= 20; i++) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        Button btn = new Button(this);
        btn.setId(i);
        final int id_ = btn.getId();
        btn.setText("button " + id_);
        btn.setBackgroundColor(Color.rgb(70, 80, 90));
        linear.addView(btn, params);
        btn1 = ((Button) findViewById(id_));
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(view.getContext(),
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }
    

    【讨论】:

    • 为什么添加按钮,然后在设置点击监听之前获取。您不能添加侦听器,然后将其添加到布局中并完成吗?
    • 最佳答案,因为您可以通过设置 id 来点击按钮 :)
    【解决方案3】:

    试试这个:

    LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
    
    Button btn = new Button(this);
    btn.setText("Manual Add");
    btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    ll.addView(btn);
    

    【讨论】:

    • 这里的 R.id.layout 指的是什么?我不断得到未解决的布局
    • @AnnaGoldberg 在您的相关 xml 文件中,您应该定义一个 LinearLayout。在这段摘录中,他们为 LinearLayout 提供了一个名为 layout 的 id,如下所示:android:id="@+id/layout"在他们的 LinearLayout xml 定义中。
    【解决方案4】:
    for (int k = 1; k < 100; k++) {
        TableRow row = new TableRow(this);
    
        innerloop:
        for (int l = 1; l < 4; l++) {
            btn = new Button(this);
            TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            layout.setWeightSum(12.0f);
            tr.weight = 0;
            btn.setLayoutParams(tr); 
            btn.setTextColor(a);
            btn.setHeight(150);
    
            btn.setWidth(150);
            btn.setId(idb);
            btn.setText("Button " + idb);
            row.addView(btn);
        }
    }
    

    【讨论】:

      【解决方案5】:

      试试这个

      private void createLayoutDynamically(int n) {
      
          for (int i = 0; i < n; i++) {
              Button myButton = new Button(this);
              myButton.setText("Button :"+i);
              myButton.setId(i);
              final int id_ = myButton.getId();
      
              LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
              layout.addView(myButton);
      
              myButton.setOnClickListener(new View.OnClickListener() {
                  public void onClick(View view) {
                      Toast.makeText(DynamicLayout.this,
                              "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                              .show();
                  }
              });
          }
      

      【讨论】:

        【解决方案6】:

        试试这个代码

         Button btn=new Button(this);
        btn.setId(btn);
        btn.setBackgroundResource(R.drawable.image);
        btn.setMinimumHeight(150);
        btn.setMinimumWidth(150);
        Relativelayout.addView(btn); 
        

        【讨论】:

          【解决方案7】:

          检查一下。

          LinearLayout ll_Main  = new LinearLayout(getActivity());
          LinearLayout ll_Row01 = new LinearLayout(getActivity());
          LinearLayout ll_Row02 = new LinearLayout(getActivity());
          
          ll_Main.setOrientation(LinearLayout.VERTICAL);
          ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
          ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
          
          final Button button01    = new Button(getActivity());
          final Button button02    = new Button(getActivity());   
          final Button button03    = new Button(getActivity());
          final Button button04    = new Button(getActivity());
          
          ll_Row01.addView(button01);
          ll_Row01.addView(button02);
          
          ll_Row02.addView(button03);
          ll_Row02.addView(button04);
          
          ll_Main.addView(ll_Row01);
          ll_Main.addView(ll_Row02);
          
          button04.setVisibility(View.INVISIBLE);
          button04.setVisibility(View.VISIBLE);
          

          【讨论】:

            【解决方案8】:
            Button btn = new Button(this);
            btn.setText("Submit");
            LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
            LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            linearLayout.addView(btn, buttonlayout);
            

            【讨论】:

              【解决方案9】:

              试试这个代码。它会正常工作..

              public class DynamicViewsActivity extends Activity {
              
              Button button;
              @Override
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  //setContentView(R.layout.activity_dynamic_views);
                  ScrollView scrl=new ScrollView(this);
                  final LinearLayout ll=new LinearLayout(this);
                  ll.setOrientation(LinearLayout.HORIZONTAL);
                  LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                          LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                  layoutParams.setMargins(100, 500, 100, 200);
                  scrl.addView(ll);
                  Button add_btn=new Button(this);
                  add_btn.setText("Click Here");
              
                  ll.addView(add_btn, layoutParams);
              
              
                  final Context context = this;
              
                  add_btn.setOnClickListener(new OnClickListener() {
              
                      @Override
                      public void onClick(View v) {
                          // TODO Auto-generated method stub
              
                          Intent intent = new Intent(context, App2Activity.class);
                          startActivity(intent);
                      }
                  });
                  this.setContentView(scrl);
              }
              }
              

              【讨论】:

                【解决方案10】:
                public void add_btn() {
                
                    lin_btn.setWeightSum(3f);
                    for (int j = 0; j < 3; j++) {
                        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params1.setMargins(10, 0, 0, 10);
                        params1.weight = 1.0f;
                
                        LinearLayout ll;
                        ll = new LinearLayout(this);
                        ll.setGravity(Gravity.CENTER_VERTICAL);
                        ll.setOrientation(LinearLayout.HORIZONTAL);
                        ll.setLayoutParams(params1);
                
                        final Button btn;
                        btn = new Button(DynamicActivity.this);
                
                        btn.setText("A"+(j+1));
                        btn.setTextSize(15);
                        btn.setId(j);
                        btn.setPadding(10, 8, 10, 10);
                
                        ll.addView(btn);
                
                        lin_btn.addView(ll);
                
                
                        btn.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                
                                if(v.getId()==0)
                                {
                                    txt_text.setText("Hii");
                                }else if(v.getId()==1)
                                {
                                    txt_text.setText("hello");
                                }else if(v.getId()==2)
                                {
                                    txt_text.setText("how r u");
                                }
                
                
                
                            }
                        });
                    }
                
                }
                

                【讨论】:

                  【解决方案11】:

                  试试下面的代码。

                  LinearLayout layout = (LinearLayout) findViewById(R.id.llayout); 
                  layout.setOrientation(LinearLayout.VERTICAL);
                  
                  Button btn = new Button(this);
                  btn.setText("Button1");
                  
                  layout.add(btn);
                  
                  btn = new Button(this);
                  btn.setText(Button2);
                  layout.add(btn);
                  

                  像这样,您可以根据需要添加按钮。

                  【讨论】:

                    【解决方案12】:

                    实际上,我在 xml 布局文件中添加了任何可以使用的东西!然后从特定 Activity 的源代码中,我通过其 id 获取对象,并使用可见性方法“玩”。

                    这是一个例子:

                    ((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);

                    【讨论】:

                    • 这不是被问到的。当人们询问动态添加时,他们的意思是没有布局。你正在做的是取消隐藏......而不是添加。
                    【解决方案13】:

                    我已使用此(或非常相似的)代码将多个 TextView 添加到 LinearLayout:

                    // Quick & dirty pre-made list of text labels...
                    String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
                    int namesLength = 5;
                    
                    // Create a LayoutParams...
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, 
                        LinearLayout.LayoutParams.FILL_PARENT);
                    
                    // Get existing UI containers...
                    LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
                    TextView label = (TextView) view.findViewById(R.id.master_label);
                    
                    TextView tv;
                    
                    for (int i = 0; i < namesLength; i++) {
                        // Grab the name for this "button"
                        final String name = names[i];
                    
                        tv = new TextView(context);
                        tv.setText(name);
                    
                        // TextViews CAN have OnClickListeners
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                label.setText("Clicked button for " + name); 
                            }
                        });
                    
                        nameButtons.addView(tv, params);
                    }
                    

                    此代码与 dicklaw795 的代码之间的主要区别在于它没有设置()和重新获取()每个 TextView 的 ID——我发现它没有必要,尽管我可能需要它来识别公共中的每个按钮处理程序例程(例如,由 onClick() 为每个 TextView 调用的例程)。

                    【讨论】:

                      【解决方案14】:
                      Button myButton = new Button(this);
                      myButton.setId(123);
                      myButton.setText("Push Me");
                      
                      
                      LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
                      LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                      ll.addView(myButton, lp);
                       myButton.setOnClickListener(new View.OnClickListener() {
                                  public void onClick(View view) {
                                      Toast.makeText(DynamicLayout.this,
                                              "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                                              .show();
                                  }
                              });
                      

                      【讨论】:

                        【解决方案15】:

                        如果你想动态添加按钮试试这个:

                        public class MainActivity extends Activity {
                        @Override
                        protected void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                            setContentView(R.layout.activity_main2);
                            for (int i = 1; i <= 5; i++) {
                                LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
                                layout.setOrientation(LinearLayout.VERTICAL);
                                Button btn = new Button(this);
                                btn.setText("    ");
                                layout.addView(btn);
                            }
                        
                        }
                        

                        【讨论】:

                          【解决方案16】:

                          您可以为您的按钮创建一个基本布局并仅动态更改特定内容,例如我为运行我正在学习的材料设计课程中的不同练习而制作的这个项目:

                          在本例中,我使用了预配置的 AppCompatButton:

                          layout_base_button.xml

                          <android.support.v7.widget.AppCompatButton
                              xmlns:android="http://schemas.android.com/apk/res/android"
                              android:id="@+id/btn_base"
                              android:layout_width="200dp"
                              android:layout_height="wrap_content"
                              android:layout_gravity="center"
                              android:layout_marginTop="8dp"
                              style="@style/RaisedButton"
                              >
                          
                          </android.support.v7.widget.AppCompatButton>
                          
                          
                          <style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
                              <item name="android:textSize">11sp</item>
                              <item name="android:textStyle">bold</item>
                          </style>
                          

                          MainActivity 中,我创建了一些实例并更改了我需要的内容,例如按钮文本和 onClick 事件:

                          <ScrollView
                              xmlns:android="http://schemas.android.com/apk/res/android"
                              xmlns:app="http://schemas.android.com/apk/res-auto"
                              xmlns:tools="http://schemas.android.com/tools"
                              android:layout_width="match_parent"
                              android:layout_height="match_parent"
                              tools:context="udemy.android.materialdesign.MainActivity">
                          
                              <LinearLayout
                                  android:id="@+id/base_layout"
                                  android:layout_width="match_parent"
                                  android:layout_height="wrap_content"
                                  android:orientation="vertical"
                                  >
                          
                              </LinearLayout>
                          
                          
                          </ScrollView>
                          
                          
                          
                          public class MainActivity extends AppCompatActivity {
                          
                          
                              @Override
                              protected void onCreate(Bundle savedInstanceState) {
                                  super.onCreate(savedInstanceState);
                                  setContentView(R.layout.activity_main);
                                  LinearLayout baseLayout = findViewById(R.id.base_layout);
                          
                                  baseLayout.addView(createButton("TextFields", baseLayout,
                                          view -> startActivity(createIntent(TextFieldsActivity.class))
                                  ));
                          
                                  baseLayout.addView(createButton("Buttons", baseLayout,
                                          view -> startActivity(createIntent(ButtonsActivity.class))
                                  ));
                          
                                  baseLayout.addView(createButton("Toolbar", baseLayout,
                                          view -> startActivity(createIntent(ToolbarActivity.class))
                                  ));
                          
                              }
                          
                              private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
                                  View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
                                  AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);
                          
                                  btnBase.setText(text);
                                  btnBase.setOnClickListener(onClickEvent);
                                  return btnBase;
                              }
                          
                              private Intent createIntent(Class<?> cls) {
                                  return new Intent(this, cls);
                              }
                          }
                          

                          抱歉迟到了……

                          【讨论】:

                            【解决方案17】:

                            我需要更加动态地创建按钮,不仅仅是在运行时,而是通过按下另一个按钮。所以点击这个按钮会在它下面动态创建更多的按钮。我建议在 Activity 上使用 ScrollView 或限制点击次数 - 所以按钮不会离开屏幕。

                            activity_main.xml

                            <?xml version="1.0" encoding="utf-8"?>
                              <androidx.constraintlayout.widget.ConstraintLayout 
                              xmlns:android="http://schemas.android.com/apk/res/android"
                              xmlns:app="http://schemas.android.com/apk/res-auto"
                              xmlns:tools="http://schemas.android.com/tools"
                              android:layout_width="match_parent"
                              android:layout_height="match_parent"
                              tools:context=".MainActivity">
                            
                            <ScrollView
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                tools:layout_editor_absoluteY="675dp">
                            
                                <LinearLayout
                                    android:id="@+id/layout"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:orientation="vertical">
                            
                                    <Button
                                        android:id="@+id/newItemButton"
                                        android:layout_width="match_parent"
                                        android:layout_height="wrap_content"
                                        android:text="Button1" />
                            
                                </LinearLayout>
                            </ScrollView>
                            </androidx.constraintlayout.widget.ConstraintLayout>
                            

                            MainActivity.java

                            public class MainActivity extends AppCompatActivity {
                            
                                @Override
                                protected void onCreate(Bundle savedInstanceState) {
                                    super.onCreate(savedInstanceState);
                                    setContentView(R.layout.activity_main);
                            
                                    LinearLayout ll = (LinearLayout)findViewById(R.id.layout); //Screen layout
                                    LinearLayout.LayoutParams params = new 
                                    LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            
                                    final Button newItemButton = findViewById(R.id.newItemButton);
                                    newItemButton.setText("Create new button");
                            
                                    newItemButton.setOnClickListener(new View.OnClickListener() {
                                        int pressCount = 1; //Count how many times button was pressed
                                        public void onClick(View v) {
                            
                                            newItemButton.setText("Button Clicked: "+pressCount);
                                            createButton(pressCount, params, ll); //Click to create new button
                                            pressCount++;
                                        }
                                    });
                            
                            
                            } //end of onCreate
                            
                            public void createButton(int id, LinearLayout.LayoutParams inputParams, LinearLayout inputLL) {
                                    Button outButton = new Button(this);
                                    outButton.setId(id);
                                    final int id_ = outButton.getId();
                                    outButton.setText("Button " + id_);
                                    inputLL.addView(outButton, inputParams);
                                }
                            
                            }//end of AppCompatActivity
                            

                            这将为您提供一个带有按钮的活动。 当您单击该按钮时,您会在其下方生成一个新按钮。 如果你生成的数量太多以至于屏幕上放不下,scrollView 会处理这个问题。

                            【讨论】:

                              【解决方案18】:

                              mainactivity.xml 写:

                              <Button
                                  android:id="@+id/search"
                                  android:layout_width="wrap_content"
                                  android:layout_height="wrap_content"
                                  android:text="Search" 
                                  android:visibility="invisible"/>
                              

                              main.java 写:

                              Button buttonSearch;
                              buttonSearch = (Button)findViewById(R.id.search);
                              buttonSearch.setVisibility(View.VISIBLE);
                              

                              【讨论】:

                                猜你喜欢
                                • 2012-07-29
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2020-02-15
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多