因为我有一个添加按钮,我可以添加文本视图和编辑文本。现在我的问题是我想问一下如果单击按钮后如何删除textview和edittext?我删除textview和edittext的按钮名称是“Button removeStaff”
这是我的代码:
_12_EventAssign.java
public class _12_EventAssign extends AppCompatActivity {
LinearLayout linearL;
View lineview;
Button addStaff;
Button removeStaff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__12__event_assign);
getSupportActionBar().setTitle("Add Event: Information");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
linearL = (LinearLayout)findViewById(R.id.add_staff);
lineview = findViewById(R.id.view1);
removeStaff = (Button)findViewById(R.id.btnaremovetaff);
removeStaff.setEnabled(false);
addStaff = (Button)findViewById(R.id.btnaddstaff);
addStaff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
removeStaff.setEnabled(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(dpToPx(300), dpToPx(40));
TextView tv = new TextView(getApplicationContext());
EditText ed = new EditText(getApplicationContext());
params.setMargins(55, 25, 0, 0);
tv.setText("Department");
tv.setTextSize(25);
tv.setTextColor(Color.BLACK);
linearL.addView(tv, params);
tv.setLayoutParams(params);
params1.setMargins(dpToPx(35), dpToPx(7), 0, 0);
ed.setBackgroundColor(getResources().getColor(R.color.colorGray));
linearL.addView(ed, params1);
ed.setLayoutParams(params1);
}
});
}
public static int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
}
我希望你能帮助我。谢谢!
答案 0 :(得分:0)
要做到这一点,只需要这样做:
removeStaff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.setVisibility(View.Gone);
ed.setVisibility(View.Gone);
}
});
此代码删除电视和版面编辑。
答案 1 :(得分:0)
您对textview和edittext有本地引用。 (电视,编辑)
你可以把它们作为班级的领域。 (将它们放在Button addStaff下面)
Button addStaff;
Button removeStaff;
TextView tv;
EditText ed;
然后在你的onClick监听器中,使用类字段设置它们。而不是本地TextView tv = ...
tv = new TextView(getApplicationContext());
为removeStaff
创建onClickListenerremoveStaff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
linearL.removeView(tv);
linearL.removeView(ed);
}
}
或者,如果您可以从线性布局中删除所有内容,则可以简单地调用removeAllViews()
removeStaff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
linearL.removeAllViews();
}
}
答案 2 :(得分:0)
尝试管理textview和editText的visibilies,如按钮
removeStaff.setOnClickListener(new View.OnClickListener(){@Override public void onClick(View view){tv.setVisibility(View.Gone); ed.setVisibility(View.Gone);}});