我正在学习为android编写代码。我从谷歌开发者网站上看到了一个示例应用程序。这基本上做的是当用户点击右上角的+
按钮时,它会向view group
添加frame layout
。该视图组包含text View
和button
,如果您点击此按钮(让我们将其命名为X按钮),则会从viewgroup
中删除frame layout
。所以他们实现了一个带有viewgroup和framelayout的列表视图。
以下是代码:
private void addItem() {
// Instantiate a new "row" view.
final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
R.layout.list_item_example, mContainerView, false);
// Set the text in the new row to a random country.
((TextView) newView.findViewById(android.R.id.text1)).setText(
COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);
// Set a click listener for the "X" button in the row that will remove the row.
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Remove the row from its parent (the container view).
// Because mContainerView has android:animateLayoutChanges set to true,
// this removal is automatically animated.
switch (view.getId()) {
case R.id.delete_button:
mContainerView.removeView(newView);
break;
}
// If there are no rows remaining, show the empty view.
if (mContainerView.getChildCount() == 0) {
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
mContainerView.addView(newView, 0);
}
现在我要做的是在用户点击X按钮时不删除整个视图组,而只删除X按钮本身。
我这样做但不起作用:
mContainerView.removeView(newView.findViewById(R.id.delete_button));
如果有人能告诉我我做错了什么:(
答案 0 :(得分:2)
我建议隐藏该视图,而不是删除该视图。
newView.findViewById(R.id.delete_button).setVisibility(View.GONE);
但是,如果您要删除该视图,则表明您正在正确执行此操作但需要刷新/无效添加delete_button
的视图,即mContainerView.invalidate()