【问题标题】:how to add button when listview is updated?更新列表视图时如何添加按钮?
【发布时间】:2015-11-18 22:30:10
【问题描述】:

我正在开发从 GCM 获取数据的应用程序,之后我在列表视图中显示数据,当从 GCM 获取新数据时,我将这些新数据添加到列表视图并使用此代码

public void updateListView2(List<FeedItem> newItems) {
    for(FeedItem item : newItems)
    {
        //Toast.makeText(this, "Title : "+item.getTitle(), Toast.LENGTH_LONG).show();

        // this to add the new items at the top of the list
        listAdapter.insert(item, 0);
    }
    // to retain the position of the listview after updated
    int lastViewIndex = listView.getFirstVisiblePosition();
    View view = listView.getChildAt(0);
    int top = (view == null) ? 0 : view.getTop() ;
    listView.setSelectionFromTop(lastViewIndex, top);
    listAdapter.notifyDataSetChanged();
       //this to add the button programitcally like "New Stories"
    Button updateBt = new Button(this);
    updateBt.setText("Updated");
    feedLayout.addView(updateBt);
}

但是当我尝试添加像“新故事”这样的按钮时,我失败了,没有看到任何内容!所以任何人都可以帮助我。

【问题讨论】:

  • 添加按钮后有没有调用listView的notifyDatasetChanged()方法?
  • 不,但我不会尝试在列表中添加按钮,我只需要通知用户 listvew 已更新,当点击按钮时,他会转到 listview 的顶部喜欢这个 FB 图片 :)

标签: android listview button


【解决方案1】:

我会玩能见度(VISIBLE && GONE)。当您获得信息时,您不必添加按钮,但在单击它(或任何您想要的事件)后使其可见并且可见性 GONE。

这可能使您更容易使用视图层次结构,因为您在 xml 布局中定义按钮(默认情况下可见性消失,在顶部或您需要的位置)并动态更改其属性。

【讨论】:

    【解决方案2】:

    最好的方法是添加该按钮并将其放置在 xml 布局文件中的任何位置并设置

    android:visibility="gone"
    

    android:visibility="invisible"
    

    当您需要显示按钮时,从 java 代码中显示它

    myButton.setVisibility(View.VISIBLE);
    

    按照这个,你不会遇到任何问题。

    【讨论】:

      猜你喜欢
      • 2013-01-13
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多