1
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("hi","onClick()");
Fragment f = ProductListFragment.newInstance(productArray);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment, f);
ft.commit();
}
});
这是主要的活动,让用户点击按钮来创建一个包含productArray数据的片段。android如何显示一个对象列表的片段
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import java.util.ArrayList;
public class ProductListFragment extends Fragment{
private ArrayList<Product> productArray;
public ArrayList<Product> getProductArray() {
return productArray;
}
public void setProductArray(ArrayList<Product> productArray) {
this.productArray = productArray;
}
public static Fragment newInstance(ArrayList<Product> productArray){
ProductListFragment productListFragment = new ProductListFragment();
productListFragment.setProductArray(productArray);
return productListFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
GridView gridView = (GridView) inflater.inflate(R.layout.product_list_fragment, container, false);
gridView.setNumColumns(2);
gridView.setGravity(Gravity.CENTER);
gridView.setAdapter( new CustomGridAdapter(getActivity(), getProductArray()));
return gridView;
}
}
这是将productArray中的数据放入网格视图的片段类,这在以前的测试中很好。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open fragment"
android:id="@+id/button"/>
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.it.fyp.fyprestaurant.ProductListFragment"
android:id="@+id/fragment"/>
</LinearLayout>
这是activity_main.xml。我知道如果我以这种方式创建片段,将会发生错误,因为productArray为null。是否需要片段标签,用于保留片段的位置或其他原因?我如何显示新的片段?请帮忙!
如何使的ArrayList是parceable [] –
Jerryc
哦,我得到这个太傻 – Jerryc
对不起,我刚刚更新到'putParcelableArrayList',这样就可以通过的ArrayList –
Emma