如何在包含布局的 android 中创建动态表单



我想创建一个动态表单,当单击添加按钮时,它将创建另一个布局,并从该表单的编辑文本中获取数据

试试这种方式。

public class DynimicForm extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
}
private void initView() {
LinearLayout relativeLayout = new LinearLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setOrientation(LinearLayout.VERTICAL);
// Creating a new TextView
final TextView tv = new TextView(this);
tv.setText("Test");
LinearLayout.LayoutParams et = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final EditText editText = new EditText(this);
editText.setHint("Enter name");
editText.setLayoutParams(et);
Button button = new Button(this);
button.setText("Click me");
button.setLayoutParams(et);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), editText.getText().toString().trim(), Toast.LENGTH_LONG).show();
tv.setText(editText.getText().toString().trim());
}
});
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
relativeLayout.addView(editText);
relativeLayout.addView(button);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}

只需进行两个活动并遵循该过程。 您可以使用 Intent 和 Get Intent 在单击按钮时获取值并将其传递给其他活动,该活动的行为与您想要的类似。

最新更新