【发布时间】:2012-02-15 22:15:03
【问题描述】:
我有一个ViewPager,它使用FragmentAdapter 来显示多个相同类型的片段。虽然这些 Fragment 基本上都是从同一个类中实例化出来的,但是它们使用的是ListView 来显示不同的信息。 (显然ListView 被ArrayAdapter 填充。)
后台服务也在运行,并不断从 Internet 接收数据。当我的后台服务通知我特定事件时,我希望能够更新 ViewPager 中的特定片段。
我怎样才能做到这一点?
非常感谢您提供代码 sn-p!
(顺便说一下,我见过this similar question,但我不知道如何使用他们的建议!)
为了更简单:
我的 ViewPager 活动:
[Fragment 0] [Fragment 1] [Fragment 2]
后台服务告诉我(通过广播)更新Fragment 1中的ListView。
编辑: 以下是示例代码:
public class ChatWindowPager extends FragmentActivity
{
private ViewPager mViewPager = null;
private ChatFragmentAdapter mAdapter = null;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_window_pager);
this.mViewPager = (ViewPager) findViewById(R.id.chatPager);
this.mAdapter = new ChatFragmentAdapter(getSupportFragmentManager());
this.mViewPager.setAdapter(this.mAdapter);
.
.
.
}
class ChatFragmentAdapter extends FragmentPagerAdapter implements ViewProvider
{
public ChatFragmentAdapter(final FragmentManager fm)
{
super(fm);
}
@Override
public Fragment getItem(final int arg0)
{
String friendId = ..... // Some initializations
ChatWindowFragment f = ChatWindowFragment.newInstance(friendId);
return f;
}
@Override
public int getCount()
{
...
}
@Override
public View getView(final int position)
{
View v = getLayoutInflater().inflate(R.layout.tab_holder, null);
.
.
.
return v;
}
}
}
现在片段是这样定义的:
public class ChatWindowFragment extends Fragment
{
public String friendId;
private ListView lv;
public static ChatWindowFragment newInstance(final String friendId)
{
ChatWindowFragment chatWindowFragment = new ChatWindowFragment();
Bundle bundle = new Bundle();
bundle.putString("friendId", friendId);
chatWindowFragment.setArguments(bundle);
return chatWindowFragment;
}
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.friendId = getArguments().getString("friendId");
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.chat_window, container, false);
this.friendId = getArguments().getString("friendId");
.
.
.
return v;
}
//The rest of the class
}
当我使用FragmentPagerAdapter 时,我不知道如何设置每个片段的标签!
(显然,我没有使用事务来添加片段!)
编辑 2: 我想知道我在做什么,是否是处理我想做的事情的正确方法......也欢迎任何其他解决方案!
【问题讨论】:
-
你尝试过我的建议了吗....
标签: android fragment android-viewpager