提问者:小点点

使用自定义ArrayAdapter将浮动操作按钮添加到ListFragment


我使用本指南创建了一个自定义ListView,它从JSON解析其数据。

https://www.bignerdranch.com/blog/customizing-android-listview-rows-subclassing/

我想添加一个浮动操作按钮到ItemListFragment,但不知道如何。

试着把它放在这里:

public ItemView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    LayoutInflater.from(context).inflate(R.layout.item_view_children, this, true);
    setupChildren();
}

但它会显示给我不想要的每个项目。

这是带有完整示例的代码:

https://github.com/bignerdranch/android-listview-custom-view/tree/master/ListItemViewDemo/src/com/bignerdranch/android/listitemviewdemo

有什么办法吗?

试图修改膨胀但不起作用:

public static ItemView inflate(ViewGroup parent) {
    ItemView itemView = (ItemView)LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_view, parent, false);
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    FloatingActionButton fab = (FloatingActionButton) inflater.inflate(R.layout.fab_view, parent, false);
    return itemView;
}

编辑:

如果我把它放在构造函数下,它可以正常工作。但是因为构造函数为每个视图调用多次,所以我必须找到一种方法只调用一次。

public ItemView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    LayoutInflater.from(context).inflate(R.layout.item_view_children, this, true);
    LayoutInflater.from(context).inflate(R.layout.fab_view, this, true);
    setupChildren();
}

共3个答案

匿名用户

解决方案终于找到了。比我想象的要简单得多。扩展ListFragment onCreateView方法的ItemListFragment调用了覆盖的方法。

所以替换:

View v = super.onCreateView(inflater, container, savedInstanceState);

与:

View v = inflater.inflate(R.layout.list_view, null); 

工作了!

还必须设置list_vew. xml:

<FrameLayout>
    <ListView android:id="@id/android:list" />
    <Button />
</FrameLayout>

匿名用户

将此代码添加到XML布局文件中,它将显示在右下角。

 <android.support.design.widget.FloatingActionButton android:id="@+id/fab"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
 android:src="@android:drawable/ic_menu_camera" />

然后在你的片段类中你可以用这段代码调用它

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           //put your code here
        }
    });

匿名用户

Xamarin Android:

RX在这里很有用。您可以在活动中订阅TabLayout的TabS选择事件。在下面的示例中,我有三个选项卡。对于第一个选项卡,我不想显示浮动操作按钮。但是,对于其他两个,我显示浮动操作按钮。

var tabs = FindViewById<TabLayout>(Resource.Id.tabLayout);
tabs.SetupWithViewPager(viewPager);

Observable.FromEventPattern<EventHandler<TabLayout.TabSelectedEventArgs>, TabLayout.TabSelectedEventArgs>(
            x => tabs.TabSelected += x, x => tabs.TabSelected -= x)
        .Subscribe(s => 
        {
            var tabLayout = s.Sender as TabLayout;
            if (tabLayout.SelectedTabPosition == 0)
              FloatingActionButton.Hide();
            else
              FloatingActionButton.Show();

            viewPager.SetCurrentItem(tabLayout.SelectedTabPosition, true);
        });