0

我想开发一种类似的应用程序(下面的链接) 如何在android中动态创建按钮? 但同时我想在另一个活动中显示它,而不是在同一个活动中。有 2 个编辑文本:1)要创建的按钮名称。2) 目标地址(用于在创建新按钮时发送的消息)。其文本正在传递给另一个活动以创建新按钮。

当我写

 public void onClick(View v) {    
            // TODO Auto-generated method stub    
        final Context context1=this;    
               if(v.getId()==R.id.button4){    
     LinearLayout l1 = (LinearLayout) findViewById(R.id.layout);      
  // R.id.layout is the layout id of the xml file for the 2nd activity.    
    Intent intent1 = new Intent(context1,PCode.class);    
    Button b = new Button(this);    
    l1.addView(b);    
    startActivity(intent1);    

 }        

该活动没有移动到第二个活动,并且程序正在终止。在同一活动中进行时,我可以创建新按钮。请帮助。

4

2 回答 2

0

在第一个活动的 onClick 中使用 Intent 发送数据:

intent = new Intent(this, PCode.class);
        intent.putExtra("EXTRA_BTN_NAME", editText.getText());
        intent.putExtra("EXTRA_WHERE", where);
        startActivity(intent);

在新活动中,您应该获取数据

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activty2);

    Intent intent = getIntent();
    String btnName = intent.getStringExtra("EXTRA_BTN_NAME");
    where= intent.getStringExtra("EXTRA_WHERE");

LinearLayout l1 = (LinearLayout) findViewById(R.id.layout);     
Intent intent1 = new Intent(context1,PCode.class);    
Button b = new Button(this);    
b.SetText(btnName);
//TODO - use the "where" parameter
l1.addView(b);
于 2013-06-12T09:21:10.140 回答
0

您可以通过意图为每个按钮传递总共 3 条消息 1) 要创建的按钮名称。2) 目标地址(用于在创建新按钮时发送的消息)。3) 按钮操作(添加/删除) 在新活动中,您使用我们的第三条意图消息处理按钮操作,即按钮操作(添加/删除)他们想要执行的操作。在新活动中,您可以使用以下代码处理

  boolean isAddButton = getIntent().getBooleanExtra("ButtonAction", false);
            if(isAddButton){
             Button myButton = new Button(this);
             myButton.setText("Add Me");
             LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
             LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,                LayoutParams.WRAP_CONTENT);
             ll.addView(myButton, lp);
            }else{
             Button myButton = new Button(this);
             myButton.setText("Remove Me");

             LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
             LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,                LayoutParams.WRAP_CONTENT);
             ll.removeView(myButton, lp);
       }
于 2013-06-12T09:26:58.803 回答