【发布时间】:2013-10-20 11:36:41
【问题描述】:
我的项目 ViewPage 中有一个带有两个片段(FragmentView1 和 FragmentView2)。
这是我的 ViewPage MainActivity,它有一个带有菜单的 ActionBar。
在这个菜单中,每个选项都应该调用 FragmentView1 中的方法来更新它。
但我真的不知道该怎么做!
这是我的 FragmentView1 中的方法:
public void loadPoema(){
// my code here
}
这是我从我的活动中调用它的地方:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.actBack:
postAtual--;
// Here I call the method in FragmentView1
return true;
default:
return super.onOptionsItemSelected(item);
}
}
在 FragmentView1 中学习有问题的方法用于更新它(非常 Fragment)加载新数据。
再次为我的水平道歉,我正在使用谷歌翻译
编辑
MainActivity XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
<android.support.v4.view.PagerTabStrip
android:id="@+id/pagerTabStrip"
android:layout_gravity="bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#cccccc"/>
</android.support.v4.view.ViewPager>
</LinearLayout>
片段 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_horizontal_margin"
android:id="@+id/fragPoema"
android:orientation="vertical" >
<TextView
android:id="@+id/txtTitulo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#0099FF"
android:typeface="serif" />
<TextView
android:id="@+id/txtPoema"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:textColor="#333333"
android:layout_gravity="center"
android:scrollbars="vertical"
android:typeface="serif" />
</LinearLayout>
和 MainActivity 代码:
private void loadViews(){
mViewPager = (ViewPager) findViewById(R.id.viewpager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(0);
}
【问题讨论】:
-
您需要保留对您的
Fragment的引用,然后拨打mFragmentView1.loadPoema();。 -
@Phil 我尝试如下调用该方法,而不必实例化:
FragmentView1.loadPoema();但显然当我想要一些活动时不起作用,只需调用MainActivity.sameMathone -
好吧,起初运行方法调用,但在 FragmentView1 的这个方法中,它运行
mDialog = new ProgressDialog(getActivity());,当我调用 MainActivity 时返回错误,因为 getActivity() -
您正试图将
local方法作为static方法调用。您需要在instance或mFragmentView1上致电loadPoema()。 -
@WaltterBarreiroNeto,这绝对不是正确的使用方法。查看this 问题以帮助找出正确的方法。
标签: android methods android-fragments android-actionbar