【问题标题】:Android: programmatically adding buttons to a layoutAndroid:以编程方式将按钮添加到布局
【发布时间】:2012-07-29 14:56:13
【问题描述】:

我正在尝试获取一个添加按钮,以根据按钮左侧的编辑文本将另一个按钮添加到布局中。重点是让一个人列出他们家中的房间,然后当他们输入每个房间时,会生成一个新按钮,以便他们可以单击房间,然后开始下一页。

我已经完成了一个 xml 布局,然后我意识到我正在“以编程方式”添加按钮,所以我以编程方式重新设计了布局,然后在 switch/case 中(这就是我执行 onclicks 的方式)添加按钮我试图向视图添加一个按钮,但它变得非常棘手。我想在edittext下方有一个滚动视图并添加按钮,当他们将所有房间添加到他们的房子时,它最终会填充他们整个家的可滚动按钮列表。有没有办法以编程方式将按钮添加到 xml 布局。我以为你可以,但我正在尝试的一切都不起作用。

感谢大家的帮助,如果您有任何建议,我们将不胜感激。

第一次编辑(响应 Tanuj 的解决方案)

我的 XML 文件(不确定我们是要使用这个还是只使用 java):

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >

<TextView
    android:id="@+id/tvAddARoom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/tvAddARoom" />

<EditText
    android:id="@+id/etAddARoom"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/etAddARoom" />


<Button
    android:id="@+id/btnAddARoom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btnAdd" />

<TextView
    android:id="@+id/tvSelectARoom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/tvSelectARoom" />

<TextView
    android:id="@+id/tvNoRooms"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/tvNoRooms" />

<Button
    android:id="@+id/btnViewAll"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btnViewAll" />

 </LinearLayout>

还有 Java。这根本不正确,因为在 java 中我正在创建整个布局而不是使用上面的布局。只是不确定我是否可以将两者联系起来。

package com.bluej.movingbuddy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
//import android.widget.ScrollView;
import android.widget.TextView;

public class EstimatorByRoom extends Activity implements OnClickListener {
String roomName;
EditText etAddARoom;
LinearLayout layout;
LinearLayout.LayoutParams layoutParam;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.estimatorbyroom);

    LayoutParams params = 
            new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);

    //create a layout
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    //create a text view
    TextView tvAddARoom = new TextView(this);
    tvAddARoom.setText("Add a Room");
    tvAddARoom.setLayoutParams(params);

    //create an edittext
    EditText etAddARoom = new EditText(this);
    etAddARoom.setHint("Living Room, Dining Room, etc.");
    etAddARoom.setLayoutParams(params);


    //create a button
    Button btnAddARoom = new Button(this);
    btnAddARoom.setText("Add");
    btnAddARoom.setLayoutParams(params);

    //adds the textview
    layout.addView(tvAddARoom);

    //add the edittext
    layout.addView(etAddARoom);
    //add the button
    layout.addView(btnAddARoom);

    //create the layout param for the layout
    LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);

    this.addContentView(layout, layoutParam);
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {

    case R.id.btnAddARoom:
        //add a room

        //this part isn't working!
        roomName = etAddARoom.getText().toString();
        Button createdButton = new Button(this);
        createdButton.setText(roomName);
        layout.addView(createdButton);
        this.addContentView(layout, layoutParam);

        //if no rooms make tvnorooms disappear

        break;
    }

}
}

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    试试这个:

        //the layout on which you are working
        LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
    
        //set the properties for button
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button");
        btnTag.setId(some_random_id);
    
        //add button to the layout
        layout.addView(btnTag);
    

    【讨论】:

    【解决方案2】:

    试试这个代码:

    LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_layout); 
    l_layout.setOrientation(LinearLayout.VERTICAL); // or HORIZONTAL
    
    Button btn1 = new Button(this);
    btn1.setText("Button_text");
    
    l_layout.addView(btn1);
    
    btn1.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
               // put code on click operation
         }
    });
    

    这是一种动态创建按钮并添加到布局中的方法。

    请记住,当您以编程方式创建按钮时,您只需使用 this 而不是 Class_name.this

    【讨论】:

      【解决方案3】:
      public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {
      
          final int TOP_ID = 3;
          final int BOTTOM_ID = 4;
      
          /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
      
              // create two layouts to hold buttons
              LinearLayout top = new LinearLayout(this);
              top.setId(TOP_ID);
              LinearLayout bottom = new LinearLayout(this);
              bottom.setId(BOTTOM_ID);
      
              // create buttons in a loop
              for (int i = 0; i < 2; i++) {
                  Button button = new Button(this);
                  button.setText("Button " + i);
                  // R.id won't be generated for us, so we need to create one
                  button.setId(i);
      
                  // add our event handler (less memory than an anonymous inner class)
                  button.setOnClickListener(this);
      
                  // add generated button to view
                  if (i == 0) {
                      top.addView(button);
                  }
                  else {
                      bottom.addView(button);
                  }
              }
      
              // add generated layouts to root layout view
              LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
              root.addView(top);
              root.addView(bottom);
          }
      
          @Override
          public void onClick(View v) {
              // show a message with the button's ID
              Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
              toast.show();
      
              // get the parent layout and remove the clicked button
              LinearLayout parentLayout = (LinearLayout)v.getParent();
              parentLayout.removeView(v);
          }
      }
      

      【讨论】:

        【解决方案4】:

        每个按钮都需要有一个 onclicklistener 来告诉它该做什么。这可以添加到您声明按钮的Java代码中。

        Button createdButton = new Button(this);
        createdButton.setOnClickListener(new OnClickListener()
        {
        
        code you want implemented
        
        }
        

        【讨论】:

          【解决方案5】:

          我会在 xml 中为您的 LinearLayout 添加一个 id:

          <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@id/llContainer"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical" >
          

          然后将您的 onClick 更改为:

          public void onClick(View v) {
              switch (v.getId()) {
          
              case R.id.btnAddARoom:
                  //add a room
                  //Find you parent layout which we'll be adding your button to:
                  LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
          
                  roomName = etAddARoom.getText().toString();
                  Button createdButton = new Button(this);
                  createdButton.setText(roomName);
                  createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,         LayoutParams.WRAP_CONTENT));
                  layout.addView(createdButton);
          
                  //if no rooms make tvnorooms disappear
          
                  break;
              }
          }
          

          【讨论】:

          • 弗拉基米尔,感谢您的关注。我尝试了您在上面提供的内容,并且同意您的想法,但是当按下添加按钮时,该应用程序似乎没有执行任何操作。还有其他想法吗?我们缺少什么?
          • onClick 会触发吗?在那里添加一个日志输出以找出答案。或者在 onClick 方法中设置断点并调试。我会为这个按钮创建一个点击监听器,这样就不需要使用 switch 语句了。
          • 好吧,所以我试着做一个日志,但是这像核爆炸一样炸毁了这个东西,所以我显然不知道如何做日志。所以,虽然我想到了一种新的方法来做到这一点。我在想,当我单击添加而不是创建按钮时,我会将房间添加到 SQLite 数据库中的房间表中。然后我将查询 SQLite 数据库并根据数据库中的数据创建按钮。如果有房间,它会给我按钮,如果没有房间,它会说“没有房间”。
          猜你喜欢
          • 1970-01-01
          • 2013-05-03
          • 2014-03-30
          • 1970-01-01
          • 2014-04-26
          • 2011-11-03
          • 2020-10-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多