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

如何在Android中动态添加按钮?,android,Android,如何在Android中动态添加按钮 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(

如何在Android中动态添加按钮

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);
查看示例

尝试以下方法:

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);

实际上,我向xml布局文件添加了任何可以使用的内容!然后从特定活动的源代码中,我通过其id获取对象,并使用visibility方法“播放”

以下是一个例子:

((微调器)findViewById(R.id.email\u微调器)).setVisibility(View.go)

请尝试此代码

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

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();
        }
    });
}
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);
    }

}
for(int i=1;i我使用此(或非常类似的)代码向线性布局添加了多个文本视图:

// 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);
}
//文本标签的快速预制作列表(&D)。。。
字符串名[]={“alpha”、“beta”、“gamma”、“delta”、“epsilon”};
int namesLength=5;
//创建布局参数。。。
LinearLayout.LayoutParams params=新的LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_内容,
LinearLayout.LayoutParams.FILL_PARENT);
//获取现有UI容器。。。
LinearLayout名称按钮=(LinearLayout)视图.findViewById(R.id.name_按钮);
TextView标签=(TextView)view.findViewById(R.id.master\u标签);
文本视图电视;
for(int i=0;i
这段代码与dicklaw795代码的主要区别在于,它没有为每个TextView设置()和重新获取()ID——我发现它没有必要,尽管我可能需要它在以后识别公共处理程序例程中的每个按钮(例如,由onClick()为每个TextView调用的按钮)。

尝试以下代码

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);
这样,您可以根据需要添加按钮。

试试这个

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();
            }
        });
    }
private void createLayoutDynamic(int n){
对于(int i=0;i
试试这个代码。它会很好用的

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);
}
}
for(int k=1;k<100;k++){
TableRow row=新的TableRow(本);
内循环:
对于(int l=1;l<4;l++){
btn=新按钮(此按钮);
TableRow.LayoutParams tr=新建TableRow.LayoutParams(LayoutParams.WRAP_内容,LayoutParams.WRAP_内容);
布局。设置权重总和(12.0f);
tr.重量=0;
btn.setLayoutParams(tr);
btn.setTextColor(a);
btn.设置高度(150);
btn.设置宽度(150);
btn.setId(idb);
btn.setText(“按钮”+idb);
行。添加视图(btn);
}
}

如果要动态添加按钮,请尝试以下操作:

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);
    }

}
公共类MainActivity扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
对于(int i=1;i
public void add_btn(){
林_btn.设定权重和(3f);
对于(int j=0;j<3;j++){
LinearLayout.LayoutParams参数1=新的LinearLayout.LayoutParams(
LayoutParams.WRAP_内容,LayoutParams.WRAP_内容);
参数1.设置边距(10,0,0,10);
参数1.重量=1.0f;
线性布局;
ll=新的线性布局(本);
ll.设置重力(重心垂直);
ll.设置方向(水平线性布局);
ll.setLayoutParams(params1);
最终按钮btn;
btn=新建按钮(DynamicActivity.this);
btn.setText(“A”+(j+1));
btn.SettexSize(15);
btn.setId(j);
btn.设置填充(10,8,10,10);
ll.addView(btn);
林_btn.addView(ll);
btn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
如果(v.getId()==0)
{
txt_text.setText(“Hii”);
}else if(v.getId()==1)
{
txt_text.setText(“你好”);
}else if(v.getId()==2)
{
txt_text.setText(“how r u”);
}
}
});
}
}

mainactivity.xml
中写入:

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

main.java
write中:

Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);
检查一下

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);

你可以为你的按钮创建一个基本布局,只动态地改变具体的内容,就像我做的这个项目是为了运行我正在学习的材料设计课程中的不同练习:

在本例中,我使用预配置的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>

抱歉迟到了…

我更新了URL,因为旧的URL给出了404。请检查我引用的页面是否正确。能否完全限定
LayoutParams
?我看到超过12个具有此名称的类。@Saeed在这个特定示例中,它是属于LinearLayout.android.widget.LinearLayout.LayoutParamsThi的LayoutParamss不是被问到的。当人们问到动态添加时,他们的意思是没有布局。你正在做的是取消隐藏…不添加。为什么要添加按钮,然后在设置单击侦听器之前获取。你不能添加侦听器,然后将其添加到布局并完成吗?最好的答案是,你可以通过设置id来单击按钮:)R.id.layout在这里指的是什么?我一直都是这样理解它的unresolved@AnnaGoldberg在相关的xml文件中,应该定义一个LinearLayout
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);
<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);
    }
}
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);