将ViewGroup动态添加到活动布局

时间:2017-04-13 15:32:14

标签: android android-layout

我想在点击任何添加按钮时将项目插入到下面视图中的列表中。我想要的是显示正在收集的所有信息,但我不确定如何以编程方式添加ViewGroup并将其插入ConstraintLayout中的正确位置,同时碰撞下面的所有相应项目。

我已经更新了按钮代码,现在我遇到了一堆其他问题,目前当点击按钮时,会显示一个TextView,其中包含" Name:"出现并正确地插入到布局中,但是当我为textView名称设置id并且它没有被记录或者我没有正确使用这些方法时,似乎没有什么事情是正确的。

按钮代码

protected void addWeap(View view)
{
    int id = 0;
    int weapons = 0;
    String weaponAdder = "";
    int weaponPointer = 0;

    ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
    ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.conLayout);
    EditText weapN = (EditText) findViewById(R.id.weapName);
    EditText weapAB = (EditText) findViewById(R.id.weapattbns);
    EditText weapDMG = (EditText) findViewById(R.id.weapDmg);
    EditText weapInfo = (EditText) findViewById(R.id.weapInfo);
    TextView proItem = (TextView) findViewById(R.id.proItem);
    String weapName = "";
    String weapAttBns = "";
    String weapdmg = "";
    String weapinfo = "";
    weapName += weapN.getText();
    weapAttBns += weapAB.getText();
    weapdmg += weapDMG.getText();
    weapinfo += weapInfo.getText();

    weapons++;
    weaponAdder += weapName + "|";
    weaponAdder += weapAttBns + "|";
    weaponAdder += weapdmg + "|";
    weaponAdder += weapinfo + "|";

    weapN.getText().clear();
    weapAB.getText().clear();
    weapDMG.getText().clear();
    weapInfo.getText().clear();

    TextView name = new TextView(this);
    params.topToBottom = weaponPointer;
    params.leftToLeft = R.id.parent;
    name.setText(R.string.namePrint);
    name.setTextColor(R.color.black);
    name.setLayoutParams(params);
    name.setPadding(8,8,0,0);
    name.setId(id);
    id++;
    weaponPointer = id;
    constraintLayout.addView(name);


    params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);

    TextView weaponName = new TextView(this);
    params.baselineToBaseline = id;
    params.leftToRight = id;
    params.rightToRight = R.id.parent;
    weaponName.setText(weapName);
    weaponName.setTextColor(R.color.black);
    weaponName.setLayoutParams(params);
    weaponName.setPadding(8,8,8,0);
    constraintLayout.addView(weaponName);


    params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
    params.leftToLeft = R.id.parent;
    params.rightToRight = R.id.parent;
    params.topToBottom = id;
    proItem.setPadding(8,8,8,0);
    proItem.setLayoutParams(params);
}

Pre-Button Push

Post-Button Push

0 个答案:

没有答案