如何将gridView替换为RecyclerView [英] How to replace gridView to RecyclerView

查看:101
本文介绍了如何将gridView替换为RecyclerView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中我以前的同事使用GridView来显示数据,但是我想将recyclerviewcardadapter一起使用,但是我没有得到如何做的信息.

I am developing an app in which my previous colleague used GridView to show data,but i want to use recyclerview with cardadapter, but I am not getting how to do that.

这是我的mainActivity代码:

Here is my code for mainActivity:

    public class ActivityCategoryList extends Activity {

GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;

// declare adapter object to create custom category list
AdapterCategoryList cla;

// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();

String CategoryAPI;
int IOConnect = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.category_list);

    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
    bar.setDisplayHomeAsUpEnabled(true);
    bar.setHomeButtonEnabled(true);
    bar.setTitle("Category");

    prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
    listCategory = (GridView) findViewById(R.id.listCategory);
    txtAlert = (TextView) findViewById(R.id.txtAlert);

    cla = new AdapterCategoryList(ActivityCategoryList.this);

    // category API url
    CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;

    // call asynctask class to request data from server
    new getDataTask().execute();

    // event listener to handle list when clicked
    listCategory.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            // TODO Auto-generated method stub
            // go to menu page
            Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
            iMenuList.putExtra("category_id", Category_ID.get(position));
            iMenuList.putExtra("category_name", Category_name.get(position));
            startActivity(iMenuList);
            overridePendingTransition(R.anim.open_next, R.anim.close_next);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_category, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
    case R.id.cart:
        // refresh action
        Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
        startActivity(iMyOrder);
        overridePendingTransition (R.anim.open_next, R.anim.close_next);
        return true;

    case R.id.refresh:
        IOConnect = 0;
        listCategory.invalidateViews();
        clearData();
        new getDataTask().execute();
        return true;

    case android.R.id.home:
        // app icon in action bar clicked; go home
        this.finish();
        overridePendingTransition(R.anim.open_main, R.anim.close_next);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

// clear arraylist variables before used
void clearData(){
    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();
}

// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{

    // show progressbar first
    getDataTask(){
        if(!prgLoading.isShown()){
            prgLoading.setVisibility(0);
            txtAlert.setVisibility(8);
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        // parse json data from server in background
        parseJSONData();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        // when finish parsing, hide progressbar
        prgLoading.setVisibility(8);

        // if internet connection and data available show data on list
        // otherwise, show alert text
        if((Category_ID.size() > 0) && (IOConnect == 0)){
            listCategory.setVisibility(0);
            listCategory.setAdapter(cla);
        }else{
            txtAlert.setVisibility(0);
        }
    }
}

// method to parse json data from server
public void parseJSONData(){

    clearData();

    try {
        // request data from Category API
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpUriRequest request = new HttpGet(CategoryAPI);
        HttpResponse response = client.execute(request);
        InputStream atomInputStream = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

        String line;
        String str = "";
        while ((line = in.readLine()) != null){
            str += line;
        }

        // parse json data and store into arraylist variables
        JSONObject json = new JSONObject(str);
        JSONArray data = json.getJSONArray("data");

        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i); 

            JSONObject category = object.getJSONObject("Category");

            Category_ID.add(Long.parseLong(category.getString("Category_ID")));
            Category_name.add(category.getString("Category_name"));
            Category_image.add(category.getString("Category_image"));
            Log.d("Category name", Category_name.get(i));

        }


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        IOConnect = 1;
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    //cla.imageLoader.clearCache();
    listCategory.setAdapter(null);
    super.onDestroy();
}


@Override
public void onConfigurationChanged(final Configuration newConfig)
{
    // Ignore orientation change to keep activity from restarting
    super.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    finish();
    overridePendingTransition(R.anim.open_main, R.anim.close_next);
}

}

这是适配器类的代码:

Class AdapterCategoryList扩展了BaseAdapter {

class AdapterCategoryList extends BaseAdapter {

    private Activity activity;
    public ImageLoader imageLoader;

    public AdapterCategoryList(Activity act) {
        this.activity = act;
        imageLoader = new ImageLoader(act);
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return ActivityCategoryList.Category_ID.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.category_list_item, null);
            holder = new ViewHolder();

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }


        holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
        holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);

        holder.txtText.setText(ActivityCategoryList.Category_name.get(position));
        imageLoader.DisplayImage(Constant.AdminPageURL+ActivityCategoryList.Category_image.get(position), holder.imgThumb);

        return convertView;
    }

    static class ViewHolder {
        TextView txtText;
        ImageView imgThumb;
    }



}

我对此并不陌生,我认为对于recyclerview,我们还需要创建一个列表类.

I am new to this, and I think for recyclerview we need to create a list class also.

如果有人对此有任何想法,您能帮我吗?

If anyone have any idea about this, can you help me?

推荐答案

我没有检查您的整个代码,但是归档此代码的关键步骤是:

I didn't check your whole code, but the key steps to archieve this is:

设置适配器

recyclerView.setAdapter(adpter);

创建并设置LayoutManager

and create and set an LayoutManager

int columns=3;
reyclerView.setLayoutManager(new GridLayoutManager(context,columns););

请参见 RecyclerView文档 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆