【问题标题】:Generate dynamically different content (from JSON) for each tab fragment为每个选项卡片段动态生成不同的内容(来自 JSON)
【发布时间】:2017-12-14 10:23:29
【问题描述】:

如何为每个新生成的片段动态设置不同的内容(来自 JSON 结构)?

这是我的 MainActivity 代码,我正在通过 Bundle 向 Fragment 传递信息:

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private GridView gridView;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title, Soups, Alcohol, Salads Lists
public final List<String> mFragmentTitleList = new ArrayList<>();
public final List<String> soupsList = new ArrayList<>();
public final List<String> alcDrinksList = new ArrayList<>();
public final List<String> saladsList = new ArrayList<>();
public final List<String> randomList = new ArrayList<>();
private ViewPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    //gridView = (GridView) findViewById(R.id.gridView);

    loaddata();
    tabLayout = (TabLayout) findViewById(R.id.tabs);
}

//Loading the JSON data, which will be used to create dynamically content such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url =
            "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            myData = response;

            JSONArray soupsArray = null;
            JSONArray alcDrinksArray = null;
            JSONArray saladsArray = null;
            JSONArray randomArray = null;
            //Log.d("response", myData);



            JSONObject object = null;
            try {
                object = new JSONObject(myData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject menuitems = null;
            try {
                menuitems = object.getJSONObject("menuitems");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                alcDrinksArray = menuitems.getJSONArray("Alcohol Drinks");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i < alcDrinksArray.length(); i++) {
                try {
                    alcDrinksList.add(String.valueOf(alcDrinksArray.getJSONObject(i).get("name")));
                    Log.d("alcDrinksList", alcDrinksList.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            try {
                soupsArray = menuitems.getJSONArray("Soups");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i < soupsArray.length(); i++) {
                try {
                    soupsList.add(String.valueOf(soupsArray.getJSONObject(i).get("name")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            try {
                    saladsArray = menuitems.getJSONArray("Salads");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i < saladsArray.length(); i++) {
                try {
                    saladsList.add(String.valueOf(saladsArray.getJSONObject(i).get("name")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            for (int i = 0; i < menuitems.length(); i++) {
                try {
                    mFragmentTitleList.add(menuitems.names().getString(i));

                    Bundle bundle = new Bundle();
//here I should pass dynamically created ArrayList<String> with data (e.g. different alcohol drinks, soups, salads, etc...) for the Fragment...
                    bundle.putStringArrayList("data", (ArrayList<String>) alcDrinksList); 
                    Log.d("bundletest", alcDrinksList.toString());
                    mFragmentList.add(new OneFragment());
                    mFragmentList.get(i).setArguments(bundle);

                    //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                    Log.d("test", String.valueOf(mFragmentTitleList));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
            }

            setupViewPager(viewPager);
            //setupGridView(gridView);
            tabLayout.setupWithViewPager(viewPager);
            // Tab ViewPager setting
            viewPager.setOffscreenPageLimit(mFragmentList.size());
            tabLayout.setupWithViewPager(viewPager);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(context, "That didn't work!", duration);
        }
    });
    queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
    viewPager.setAdapter(adapter);
}

/*private void setupGridView(GridView gridView) {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, alcDrinksList);
    gridView = (GridView) findViewById(R.id.gridView);
    gridView.setAdapter(adapter);
}*/

//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
        super(fm);
        this.mFragmentList = fragments;
        this.mFragmentTitleList = titleLists;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList == null ? 0 : mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}

}

这是我的片段类:

public class OneFragment extends Fragment {
private List<String> contentList = new ArrayList<>();
ArrayAdapter<String> adapter;
GridView gridView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    contentList = getArguments().getStringArrayList("data");
    Log.d("contentList", contentList.toString());

    View view = inflater.inflate(R.layout.fragment_one, null);

    gridView = (GridView) view.findViewById(R.id.gridView);
    adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, contentList);
    gridView.setAdapter(adapter);

    return view;
}
}

目前我在每个片段上都有所有的酒精饮料。我知道我可以将其设置为静态/通过调用 JSON 名称.../,这会容易得多,但我希望我的应用程序具有可扩展性和开源性,这就是为什么我要动态创建所有内容(根据传递 JSON 文件 :) )。

所以,最后我应该有 标签 /Alcohol Drinks/ 与酒精饮料 标签 /Soups/ 与汤 标签 /Salads/ 与沙拉...

【问题讨论】:

    标签: java android json android-fragments tabs


    【解决方案1】:

    以这种方式更改您的 OneFragment 构造函数。

    从此

    public OneFragment() {
    // Required empty public constructor
    }
    

    收件人

    public OneFragment(Context context,ArrayList<String> contentList ) {
        this.context = context;
        this.contentList = contentList ;
    }
    

    更改OneFragment onCreate() 以获取直接内容列表,例如沙拉列表,汤列表将添加到 setsetupViewPager() 中,如下代码

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //contentList will get data from constructor
        Log.d("contentList", contentList.toString());
    
        View view = inflater.inflate(R.layout.fragment_one, null);
    
        gridView = (GridView) view.findViewById(R.id.gridView);
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, contentList);
        gridView.setAdapter(adapter);
    
        return view;
    }
    

    将此方法添加到您的 ViewPagerAdapter 中。

     public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
     }
    

    并对ViewPagerAdapter构造函数进行更改

    从此

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
        super(fm);
        this.mFragmentList = fragments;
        this.mFragmentTitleList = titleLists;
    }
    

    收件人

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    

    现在根据您的需要制作其他 3 个必需的Fragment。即沙拉、汤等,如 OneFragment 并传递该数据,删除 for 循环 添加 Bundle bundle = new Bundle(); 和所有数据的位置。在 setupViewPager() 中直接添加这样的。 像这样改变方法。

    private void setupViewPager(ViewPager viewPager) {
       adapter = new ViewPagerAdapter(getSupportFragmentManager());
    
       adapter.addFrag(new OneFragment(context,alcDrinksList));
       adapter.addFrag(new SaladFragment(context,saladsArray));
       adapter.addFrag(new SoupFragment(context,soupsArray));
       viewPager.setAdapter(adapter);
    }
    

    希望这会有所帮助。

    【讨论】:

    • 这些列表只是为了确保我的代码有效。从理论上讲,每次创建选项卡时,我可能也需要创建一个新列表(在 for 循环中)。我的意思是当你有例如{“汤”:[{“名称”:“花椰菜奶油”,...},{“名称”:“鲑鱼”,...}]。所以当一个新标签例如创建了汤,它应该只绑定关于汤的信息,然后我可以调用 .get("name") 并获取汤的名称以将其显示在片段上......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多