如何从布局添加和删除视图?
Answers:
我这样做是这样的:
((ViewManager)entry.getParent()).removeView(entry);
(ViewGroup):)
使用ViewStub并指定要切换的视图的布局。查看:
mViewStub.setVisibility(View.VISIBLE) or mViewStub.inflate();
消失:
mViewStub.setVisibility(View.GONE);
这是最好的方法
LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them
lp.removeViewAt(0); // and so on
如果您具有xml布局,则无需动态添加。只需调用
lp.removeViewAt(0);
要将视图添加到布局,可以使用类的addView方法ViewGroup。例如,
TextView view = new TextView(getActivity());
view.setText("Hello World");
ViewGroup Layout = (LinearLayout) getActivity().findViewById(R.id.my_layout);
layout.addView(view);
也有许多删除方法。查看ViewGroup的文档。从布局中删除视图的一种简单方法是,
layout.removeAllViews(); // then you will end up having a clean fresh layout
要更改可见性:
predictbtn.setVisibility(View.INVISIBLE);
删除:
predictbtn.setVisibility(View.GONE);
您可以使用addView或removeView
Java的
// Root Layout
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// TextView
TextView textView = new TextView(context);
textView.setText("Sample");
// Add TextView in LinearLayout
linearLayout.addView(textView);
// Remove TextView from LinearLayout
linearLayout.removeView(textView);
科特林:
// Root Layout
val linearLayout = LinearLayout(context)
linearLayout.gravity = Gravity.CENTER
linearLayout.orientation = LinearLayout.VERTICAL
// TextView
val textView = TextView(context)
textView.text = "Sample"
// Add TextView in LinearLayout
linearLayout.addView(textView)
// Remove TextView from LinearLayout
linearLayout.removeView(textView)
您好,如果您是android新手,请使用这种方法将视图应用到GONE是一种方法,否则,请握住父视图,然后从那里移除子项.....否则,请获取父布局并使用此方法方法,删除所有子对象parentView.remove(child)
我建议使用GONE方法...
我正在使用开始和计数方法删除视图,我在线性布局中添加了3个视图。
view.removeViews(0,3);
添加此扩展名:
myView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parent = parent as? ViewGroup ?: return
parent.removeView(this)
}
以下是一些选择:
// Built-in
myViewGroup.addView(myView)
// Null-safe extension
fun ViewGroup?.addView(view: View?) {
this ?: return
view ?: return
addView(view)
}
// Reverse addition
myView.addTo(myViewGroup)
fun View?.addTo(parent: ViewGroup?) {
this ?: return
parent ?: return
parent.addView(this)
}