如何在Java类中为元素xml设置id?

时间:2015-06-15 02:12:59

标签: java android

RelativeLayout.LayoutParams txtP1 = new RelativeLayout.LayoutParams(txtPlus1.getLayoutParams());
txtP1.leftMargin = Math.round((btnPlus1.getLeft() + (btnPlus1.getWidth()/2)) - (txtPlus1.getWidth()/2));
txtP1.topMargin = Math.round((btnPlus1.getTop() + (btnPlus1.getHeight()/2)) - (txtPlus1.getHeight()/2));
txtPlus1.setLayoutParams(txtP1);

RelativeLayout.LayoutParams txtP5 = new RelativeLayout.LayoutParams(txtPlus5.getLayoutParams());
txtP5.leftMargin = Math.round((btnPlus5.getLeft() + (btnPlus5.getWidth()/2)) - (txtPlus5.getWidth()/2));
txtP5.topMargin = Math.round((btnPlus5.getTop() + (btnPlus5.getHeight()/2)) - (txtPlus5.getHeight()/2));
txtPlus5.setLayoutParams(txtP5);

RelativeLayout.LayoutParams txtM1 = new RelativeLayout.LayoutParams(txtMinus1.getLayoutParams());
txtM1.leftMargin = Math.round((btnMinus1.getLeft() + (btnMinus1.getWidth()/2)) - (txtMinus1.getWidth()/2));
txtM1.topMargin = Math.round((btnMinus1.getTop() + (btnMinus1.getHeight()/2)) - (txtMinus1.getHeight()/2));
txtMinus1.setLayoutParams(txtM1);

我想为txtv设置一个id。 和.. 如何更改此元素的其他属性?

1 个答案:

答案 0 :(得分:0)

您可以致电setId来设置ID。

public final static int MY_ID = 2;

TextView tv = new TextView(this);
tv.setId(MY_ID);

您可以使用属性名称设置属性。请参阅TextView documentation

tv.setText("Some text");