合并自定义列表视图和选项卡

时间:2016-01-12 04:46:54

标签: android json android-fragments android-listview

IconTextTabsActivity.java

public class IconTextTabsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_tab_favourite,
        R.drawable.ic_tab_call,
        R.drawable.ic_tab_contacts
};


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

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

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), "ONE");
    adapter.addFrag(new TwoFragment(), "TWO");
    adapter.addFrag(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}


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

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

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

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

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

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

OneFragment.java

public class OneFragment extends Fragment  implements SwipeRefreshLayout.OnRefreshListener{



private static final String TAG = PatientList.class.getSimpleName();
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;

// Movies json url
private static final String url = "http://192.168.0.102/test/apps.php";
private ProgressDialog pDialog;
private List<Patient> patientList = new ArrayList<Patient>();
private ListView listView;
private CustomListAdapter listadapter;

private SwipeRefreshLayout swipeRefreshLayout;

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
    View view = inflater.inflate(R.layout.patientlist_listview, container, false);

    listView = (ListView) view.findViewById(R.id.list);
    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);

    listadapter = new CustomListAdapter(this, patientList);
    listView.setAdapter(listadapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    // getActionBar().setBackgroundDrawable(
    //        new ColorDrawable(Color.parseColor("#00BBD3")));

    swipeRefreshLayout.setOnRefreshListener(this);

    /**
     * Showing Swipe Refresh animation on activity create
     * As animation won't start on onCreate, post runnable is used
     */
    swipeRefreshLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    swipeRefreshLayout.setRefreshing(true);
                                    fetchPatients();
                                }
                            }
    );

    listView.setAdapter(listadapter);

    // Click event for single list row
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(IconTextTabsActivity.this, "row " + position + " was pressed", Toast.LENGTH_LONG).show();
            switch (position) {
                case 0:
                    TextView c =(TextView)view.findViewById(R.id.title);
                    String item = c.getText().toString();
                    Log.d("id", item);
                    break;

                case 1:
                    break;
            }

        }

    });


    return view;

}
/**
 * This method is called when swipe refresh is pulled down
 */
@Override
public void onRefresh() {
    fetchPatients();
}
/**
 * Fetching movies json by making http call
 */
private void fetchPatients() {

    // showing refresh animation before making http call
    swipeRefreshLayout.setRefreshing(true);

    // appending offset to url
    //String url = URL_TOP_250 + offSet;

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();
                    Log.d("id", "hi") ;
                    // Parsing json
                    // reset the list
                    patientList.clear();
                    listadapter.notifyDataSetChanged();

                    for (int i = 0; i < response.length();i++) {
                        try {
                            Log.d("id","hi1") ;
                            Log.d("i","i:"+i);

                            Patient patient = new Patient();

                            Log.d("length", "length:" + response.length());
                            JSONObject objid= response.getJSONObject(i);
                            //get id
                            patient.setTitle(objid.getString("id"));

                            //Log.d("i","i:"+i);
                            //obj= response.getJSONObject(i+1);
                            //get image url second item
                            JSONObject objimage= response.getJSONObject(++i);
                            patient.setThumbnailUrl(objimage.getString("image"));
                            //Log.d("i","i:"+i);


                            //patient.setTitle(obj.getString("id"));
                            //patient.setThumbnailUrl(obj.getString("image"));


                            // Log.d("id",obj.getString("id")) ;
                            //  Log.d("image",obj.getString("image")) ;
                            /*movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);
                            */

                            // adding movie to movies array
                            if(i%2==1)
                                patientList.add(patient);

                            // updating offset value to highest value
                            //if (i >= offSet)
                            //  offSet = i;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    listadapter.notifyDataSetChanged();

                    // stopping swipe refresh
                    swipeRefreshLayout.setRefreshing(false);

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();
            Toast.makeText(view.getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            // stopping swipe refresh
            swipeRefreshLayout.setRefreshing(false);

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

//public PatientList() {
//Required empty public constructor

//}

}

错误消息

Error:(75, 38) error: incompatible types: OneFragment cannot be converted to Context
Error:(72, 45) error: incompatible types: OneFragment cannot be converted to Activity
Error:(223, 32) error: cannot find symbol variable view
Error:(106, 52) error: not an enclosing class: IconTextTabsActivity

我想将列表视图和tab活动与json合并。但是,它会在以下4行中得到错误,我不知道如何解决它。

    listadapter = new CustomListAdapter(this, patientList);

    pDialog = new ProgressDialog(this);

    Toast.makeText(IconTextTabsActivity.this, "row " + position + " was pressed", Toast.LENGTH_LONG).show();

    public PatientList() {
//Required empty public constructor

}

请给我一些帮助来解决这个问题。谢谢。

1 个答案:

答案 0 :(得分:0)

//打开您的Main Activity并从TabActivity扩展该类。

public class AndroidTabAndListView extends TabActivity

//现在在res下打开main.xml - &gt;布局文件夹并创建一个tabview。

//为选项卡创建活动并从ListActivity扩展类

public class Activity extends ListActivity 

//为列表视图创建xml布局。

//每个标签可能都需要一个图标,因此每个标签都有设计图标。