LinearLayout linContact = (LinearLayout) mView.findViewById(R.id.linContacts);
LinearLayout.LayoutParams leftGravityparas = new LinearLayout.LayoutParams(0,LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams rightGravityParams = new LinearLayout.LayoutParams(30, 30);
for (int i = 0; i < contactList.size(); i++) {
final ClsAdviserData contact = .contactList.get(i);
if (contact.isSelected()) {
linearLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams linMainparam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(linMainparam);
linMainparam.setMargins(0, 10, 0, 0);
leftGravityparas.gravity = Gravity.LEFT;
leftGravityparas.weight = 0.9f;
TextView txtContact = new TextView(getActivity());
txtContact.setTextSize(16);
// txtContact.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
txtContact.setLayoutParams(leftGravityparas);
txtContact.setId(i);
leftGravityparas.setMargins(0, 10, 0, 0);
txtContact.setPadding(20, 10, 10, 10);
txtContact.setText(contact.getName());
linearLayout.addView(txtContact, leftGravityparas);
rightGravityParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
rightGravityParams.weight = 0.1f;
final ImageView imgDelContact = new ImageView(getActivity());
imgDelContact.setLayoutParams(rightGravityParams);
imgDelContact.setTag(i);
imgDelContact.setClickable(true);
imgDelContact.setOnClickListener(this);
imgDelContact.setImageResource(R.drawable.ic_close_grey);
linearLayout.addView(imgDelContact, rightGravityParams);
// linContact.setTag(i);
linContact.addView(linearLayout);
imgDelContact.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Toast ==>" + contact.getName() + v.getTag(), Toast.LENGTH_SHORT).show();
// linContact.removeViewAt((Integer) v.getTag());
linearLayout.setVisibility(View.GONE);
// lin.removeViewAt((Integer)v.getTag());
}
});
}
}
我编写了上面的代码来动态创建文本域和按钮;但是现在我需要在单击按钮时删除2个文本字段和一个按钮。我该怎么做?
答案 0 :(得分:2)
添加 -
在使用LinearLayout
linearLayout.addView(txtContact);
linearLayout.addView(imgDelContact);
隐藏 -
隐藏视图,以便您可以在需要时再次获取
imgDelContact.setVisibility(View.GONE);
txtContact.setVisibility(View.GONE);
删除 -
或者,如果您不想再次使用它,也可以删除。
linearLayout.removeView(txtContact);
linearLayout.removeView(imgDelContact);
答案 1 :(得分:2)
删除任何可以使用的视图
aLinearLayout.removeView(view)// to remove particular view
aLinearLayout.removeViewAt(position);// to remove view from particular position
答案 2 :(得分:0)
如果您正在动态创建视图,而只需要删除所有视图,则只需使用
aLinearLayout.removeAllViews();
这将清除布局。