如标题所述,我想了解如何在按下另一个 Activity 中的另一个按钮时动态创建按钮。这是通过 Android SDK 完成的。
基本上,我有两个 Activity ,MainActivity 和 SecondaryActivity,您在 SecondaryActivity 中输入一些信息,标题、文本、ID 等等。当您单击“保存”按钮时,它会向 MainActivity 发送一些信息(不是问题)。除了发送信息,我还需要在 MainActivity 中创建一个全新的按钮。
关于如何完成这件事有什么建议吗?
谢谢。
编辑 1
public void CreateNewButton(View view)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
TextView newTextView = new TextView(this);
int id = rand.nextInt(100);
int newId;
newTextView.setVisibility(View.VISIBLE);
newTextView.setId( R.id.new_button + id );
newTextView.setText("New Item");
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intent = new Intent(getBaseContext(), SecondActivity.class);
startActivity(intent);
}
});
lineLayout.addView(newTextView);
}
此代码生成新的 TextView(决定对其进行更改)但现在我遇到的问题是 newTextView.setText();需要从其他 Activity 中获取文本
newTextView.setText(i.getData().toString());
将它放在 CreateNewButton(View view) 方法中会导致错误,因为从技术上讲,它试图从中获取的字段中没有数据。
手头的问题是我需要使用尚未创建的新帐户的名称创建新的 TextView 字段。如果这有意义的话。
最佳答案
我假设您想将此按钮添加到 LinearLayout:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Button button = new Button(this);
button.setText("I'm a button!");
// add whatever other attributes you want to the button
linearLayout.addView(button);
关于android - 如何在android中动态创建另一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17710810/