【发布时间】:2016-08-28 10:48:38
【问题描述】:
我正在学习为 android 编写代码。我从谷歌开发者网站上看到了一个示例应用程序。这基本上是每当用户点击右上角的+ 按钮时,它会在frame layout 中添加一个view group。该视图组包含一个text View 和一个button,如果您单击此按钮(我们将其命名为X 按钮),它将从frame layout 中删除viewgroup。所以他们实现了一个带有视图组和框架布局的列表视图。
代码如下:
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));
如果有人能告诉我我做错了什么:(
【问题讨论】:
标签: java android xml android-studio viewgroup