我在使用片段时遇到了问题。实际上,我试图将一些参数传递给我的Activity中的Fragment。问题是我的getArguments()
调用总是返回null。这是我的代码:
AlbumUser.java:
public class AlbumUser extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_user);
String albumId = getIntent().getStringExtra("albumId");
String albumName = getIntent().getStringExtra("albumName");
String albumAuthor = getIntent().getStringExtra("albumAuthor");
String coverUrl = getIntent().getStringExtra("coverUrl");
getFragmentManager().beginTransaction().replace(R.id.fragmentAlbum, Album.newInstance(albumId,albumName,albumAuthor,coverUrl)).commit();
}
}
Album.java:
public class Album extends Fragment {
private String albumId;
private String albumName;
private String albumAuthor;
private String coverUrl;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.activity_album, container, false);
Bundle args = getArguments();
albumId = args.getString("albumId");
albumName = args.getString("albumName");
albumAuthor = args.getString("albumAuthor");
coverUrl = args.getString("coverUrl");
return view;
)
public static Album newInstance(final String albumId, final String albumName, final String albumAuthor, final String coverUrl) {
final Album album = new Album();
final Bundle bundle = new Bundle();
bundle.putString("albumId", albumId);
bundle.putString("albumName", albumName);
bundle.putString("albumAuthor", albumAuthor);
bundle.putString("coverUrl", coverUrl);
album.setArguments(bundle);
return album;
}
}
activity_album.xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/fragmentAlbum"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.jeff.facebookphotocast.Album" />
<include layout="@layout/toolbar"/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
请帮助我,我要死了^^ 谢谢:))
答案 0 :(得分:4)
布局XML
<fragment
android:id="@+id/fragmentAlbum"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.jeff.facebookphotocast.Album" />
在没有任何参数的情况下实例化您的Album
片段。这就是getArguments()
返回null的原因。
如果您想要始终为片段提供一些参数,请将此部分布局替换为例如一个空的FrameLayout
容器,并使用FragmentTransaction#add()
将您的fragment-with-args放入容器中。