【发布时间】:2010-09-27 16:00:49
【问题描述】:
如何在布局中添加和删除视图?
【问题讨论】:
-
什么样的布局?您能粘贴您正在处理的部分代码吗?
-
这是如何准备好的?
标签: android
如何在布局中添加和删除视图?
【问题讨论】:
标签: android
我是这样做的:
((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);
【讨论】:
要向布局添加视图,您可以使用ViewGroup 类的addView 方法。例如,
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
【讨论】:
来自 Sameer 和 Abel Terefe 的精彩回答。但是,当您删除视图时,在我的选项中,您希望删除具有特定 ID 的视图。这是你如何做到的。
1、创建视图时给它一个id:
_textView.setId(index);
2、移除带有id的视图:
removeView(findViewById(index));
【讨论】:
为了改变可见性:
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)
【讨论】:
添加这个扩展:
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)
}
【讨论】:
嗨,如果你是 android 新手,请使用这种方式 应用您的视图使其消失 GONE 是一种方式,否则,获取父视图并删除 孩子从那里...... 否则获取父布局并使用此方法删除所有子布局 parentView.remove(child)
我建议使用 GONE 方法...
【讨论】:
我正在使用 start 和 count 方法删除视图,我在线性布局中添加了 3 个视图。
view.removeViews(0, 3);
【讨论】: