如何根据用户输入更改ListView的第一项

时间:2017-01-24 05:48:08

标签: java android listview android-volley android-calendar

我有一个物化日历,其中包含几天的某些事件。 所有这些事件也列在列表视图中。 如果我点击了日历上的特定日期,我就是这么做的 然后,如果列表视图的项目中有此日期,那么该项目将在列表视图中排在第一位。 日历和列表视图都处于不同的活动中。所以我保存点击日期并将其转移到其他活动中:

materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {

                Date dt=date.getDate();
                String str1=String.valueOf(timeZoneFormat.format(dt));
                Intent i = new Intent(MainActivity.this, CalendarList.class);
                i.putExtra("datec",str1);
                startActivity(i);
                // close this activity
                finish();
            }
        });

并在其他活动中得到它:

    Intent i = getIntent();
    i.getData();
    date2 = i.getStringExtra("datec");

And my listview is display using this code:

     caladata();
        calList = new ArrayList < > ();
        adapter = new CalendarListAdapter(this, calList);
        listView.setAdapter(adapter);


 private void caladata() {

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

        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
                new Response.Listener < String > () {
                    @Override
                    public void onResponse(String response) {
                        //                        Log.d(TAG, response.toString());
                        //                        hidePDialog();
                        JSONObject object = null;
                        try {
                            object = new JSONObject(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        JSONArray jsonarray = null;

                        try {
                            jsonarray = object.getJSONArray("Table");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        for (int i = 0; i < jsonarray.length(); i++) {
                            try {
                                JSONObject obj = jsonarray.getJSONObject(i);
                                Calenndar_Model movie = new Calenndar_Model();
                                String str = obj.getString("eventdate").replaceAll("\\D+","");
                                String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
                                DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                                timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

                                Date time = new Date(Long.parseLong(upToNCharacters));
                                movie.setDate(String.valueOf(timeZoneFormat.format(time)));

                                movie.setColor(obj.getString("eventcolor"));

                                movie.setAutoid(obj.getString("autoid"));

//                                Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();

                                if (date2.equals(time)){

                                // adding movie to movies array
                                calList.add(0,movie);
                                   } calList.add(movie);
                                // Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();

                            } catch (JSONException e) {
                                // Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                            }

                        }



                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map < String, String > getParams() {
                Map < String, String > params = new HashMap < String, String > ();
                params.put("clientid", get1);
                return params;
            }
        };
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }

我的适配器代码:

   public class CalendarListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Calenndar_Model> movieList;
    private String[] bgColors;

    public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
        this.activity = activity;
        this.movieList = movieList;
    }

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

    @Override
    public Object getItem(int location) {
        return movieList.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.calendar_listrow, null);

        ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView date1 = (TextView) convertView.findViewById(R.id.date1);

        title.setText(movieList.get(position).getHost());
        date1.setText(movieList.get(position).getDate());



        return convertView;
    }

}

因此,如何更新此代码以在列表视图顶部显示单击日期(项目)。

请指导。

3 个答案:

答案 0 :(得分:0)

您可以headerView添加ListView ..

View header = getLayoutInflater().inflate(R.layout.header, null);
listView.addHeaderView(header);

最后将适配器设置为列表视图。

listView.setAdapter(youradapter);

答案 1 :(得分:0)

我认为您希望在列表顶部显示所选日期,而列表视图仍需要滚动。

您编写的上述代码会将所选日期置于最前面,但已排序的行为将受到影响。

更好的解决方案是按原样添加列表中的项目,然后滚动到特定的选定日期。

在遍历表的for循环中,添加以下代码。

selectedItemPos = 0;
if (date2.equals(time)) {
    selectedItemPos = i;
}

刷新列表视图后。使用以下方法滚动到selectedPos

getListView().smoothScrollToPositionFromTop(position,offset,duration);

<强>参数

  • position:滚动到的位置(我们的案例selectedPos
  • offset:滚动完成时距视图顶部位置的所需距离(
  • 持续时间:用于滚动的毫秒数

修改

您需要更新的部分代码。请参阅功能caladata()中的更新行。 listview在这种情况下需要是最终的。

for (int i = 0; i < jsonarray.length(); i++) {
   try {
        JSONObject obj = jsonarray.getJSONObject(i);
        Calenndar_Model movie = new Calenndar_Model();
        String str = obj.getString("eventdate").replaceAll("\\D+","");
        String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
        DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");                                        timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

        Date time = new Date(Long.parseLong(upToNCharacters));
        movie.setDate(String.valueOf(timeZoneFormat.format(time)));
        movie.setColor(obj.getString("eventcolor"));

        movie.setAutoid(obj.getString("autoid"));
        // **Code updated**
        selectedPos = 0;
        if (date2.equals(time)){
             selectedItemPos = i;
        }
        // Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
    // Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}

adapter.notifyDataSetChanged();
 // **Code updated**
listview..smoothScrollToPositionFromTop(selectedPos,0,300);

我认为这会有所帮助。快乐编码

答案 2 :(得分:0)

将以下代码放在Adapter中,并从适配器实例中调用此方法。如果您不清楚,请粘贴您的适配器代码并让我帮助您。

public void swapList(List<Object> objectList) {
        this.objectList = objectList;
        notifyDataSetChanged();
    }

更新了适配器类:

public class CalendarListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Calenndar_Model> movieList;
    private String[] bgColors;

    public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
        this.activity = activity;
        this.movieList = movieList;
    }

     public void swapList(List<Calenndar_Model> movieList) {
        this.movieList = movieList;
        notifyDataSetChanged();
    }

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

    @Override
    public Object getItem(int location) {
        return movieList.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.calendar_listrow, null);

        ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView date1 = (TextView) convertView.findViewById(R.id.date1);

        title.setText(movieList.get(position).getHost());
        date1.setText(movieList.get(position).getDate());



        return convertView;
    }

}

在calList中更改/排序后,使用此代码刷新列表。

adapter.swapList(calList);