我的问题从这个问题继续:Android : How to programatically set layout_constraintRight_toRightOf "parent"。
我编写了以下代码,应将新的TextView约束在ConstraintLayout的左侧(btnSendL)或右侧(btnSendR)。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ConstraintLayout clMessagesContainer = (ConstraintLayout) findViewById(R.id.clMessagesContainer);
final EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
Button btnSendL = (Button) findViewById(R.id.btnSendL);
Button btnSendR = (Button) findViewById(R.id.btnSendR);
btnSendL.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
TextView lblNxtMessage = new TextView(MainActivity.this);
lblNxtMessage.setLayoutParams(new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT));
lblNxtMessage.setText(txtMessage.getText().toString());
clMessagesContainer.addView(lblNxtMessage);
ConstraintSet csL = new ConstraintSet();
csL.clone(clMessagesContainer);
csL.connect(lblNxtMessage.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0);
csL.connect(lblNxtMessage.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
csL.applyTo(clMessagesContainer);
}
});
btnSendR.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
TextView lblNxtMessage = new TextView(MainActivity.this);
lblNxtMessage.setLayoutParams(new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT));
lblNxtMessage.setText(txtMessage.getText().toString());
clMessagesContainer.addView(lblNxtMessage);
ConstraintSet csR = new ConstraintSet();
csR.clone(clMessagesContainer);
csR.connect(lblNxtMessage.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
csR.connect(lblNxtMessage.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
csR.applyTo(clMessagesContainer);
}
});
}
但是,每次我单击任一按钮时,都会对所有已创建的TextView进行此操作,而不仅仅是在最新的onClickListenerMethod内部创建的TextView。我该如何解决?
答案 0 :(得分:0)
之所以会发生这种情况,是因为每个新创建的View
的默认ID
为-1
,因此对其应用的约束会影响所有Views
的{{1}}
要解决此问题,您需要为每个创建的ID
生成唯一的ID
。最简单的方法是使用View
类中的静态方法generateViewId()
。用法如下:
View
答案 1 :(得分:0)
我推荐TextView lblNxtMessage = new TextView(MainActivity.this);
lblNxtMessage.setId(View.generateViewId());
到新的setId()
TextView
示例
lblNxtMessage.setId(View.generateViewId());