如何刷新片段上的列表视图
Posted
技术标签:
【中文标题】如何刷新片段上的列表视图【英文标题】:how to refresh listview on a fragment 【发布时间】:2016-03-05 23:45:49 【问题描述】:我需要你的帮助
我在片段上有一个列表视图(BaseAdapter)(我用 SQLite 填充它),这个片段在带有 Swipe 的 pageViewer 上。 另外,ActionBar 上有一个按钮,当我单击该按钮时,将下载数据(外部 SQLServer)并与 SQLite 同步。
image
我的问题:
当我点击按钮时,listview 如何在 Activity 上直观地刷新/更新它?
【问题讨论】:
如果您使用 CursorAdapter 作为 ListView 的适配器并使用 LoaderManager.LoaderCallbacks developer.android.com/reference/android/app/…,则很容易。这意味着采用 ContentProvider 来允许 CursorLoader 了解数据更改,但这并不难用所有可以为您执行此操作的库来实现(SimpleSQLConfig 就是其中之一) 我在 ListView 中使用 BaseAdapter 【参考方案1】:它很简单,您可以在单击下载数据按钮时为列表视图设置适配器,并为适配器调用 notifydatasetchanged 方法。
package com.example.alarmapp2;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
@SuppressLint("SimpleDateFormat")
public class MainActivity extends ActionBarActivity implements OnClickListener
private ImageView addButton;
private TextView tvDate;
private TimePicker tvTime;
private EditText message;
private Button save, cancel;
private DataBaseHelper dbhelper;
private ListView alarmListView;
private PendingIntent pendingIntent;
private AlarmManager manager;
private static MainActivity inst;
public static MainActivity instance()
return inst;
@Override
public void onStart()
super.onStart();
inst = this;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new DataBaseHelper(this);
alarmListView= (ListView) findViewById(R.id.alarm_list);
addButton = (ImageView) findViewById(R.id.addButton);
addButton.setOnClickListener(this);
manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//setting data to list view
addListDetails();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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.
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
@SuppressLint("InflateParams")
@Override
public void onClick(View v)
switch (v.getId())
case R.id.addButton:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
LayoutInflater layoutInflater = LayoutInflater.from(this);
// setting layout view
View promptView = layoutInflater.inflate(R.layout.alaram_popup, null, false);
alertDialogBuilder.setView(promptView);
tvDate = (TextView) promptView.findViewById(R.id.select_date);
tvDate.setOnClickListener(this);
tvTime = (TimePicker) promptView.findViewById(R.id.select_time);
/*tvTime.setOnClickListener(this);*/
tvTime.setIs24HourView(true);
message = (EditText) promptView.findViewById(R.id.message);
save = (Button) promptView.findViewById(R.id.save);
cancel = (Button) promptView.findViewById(R.id.cancel);
alertDialogBuilder.setCancelable(true);
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
alertDialog.show();
save.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
if (tvDate.getText().toString().length() == 0)
tvDate.setError("Select Date");
/*else if (tvTime.getText().toString().length() == 0)
tvTime.setError("Select Date");
*/else if (message.getText().toString().length() == 0)
message.setError("Select Date");
else
String timeMin="";
dbhelper=new DataBaseHelper(MainActivity.this);
if(tvTime.getCurrentMinute()<10)
timeMin="0"+tvTime.getCurrentMinute();
else
timeMin=""+tvTime.getCurrentMinute();
AlarmDoa doa = new AlarmDoa();
doa.setDate(tvDate.getText().toString());
doa.setTime(tvTime.getCurrentHour()+":"+timeMin);
doa.setMessage(message.getText().toString());
long Status=dbhelper.addalarm(doa);
alertDialog.dismiss();
if(Status!=0)
//settin data on click of button
addListDetails();
Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT).show();
setAlarm(tvDate.getText().toString(),tvTime.getCurrentHour()+":"+tvTime.getCurrentMinute(),message.getText().toString());
else
Toast.makeText(MainActivity.this, "Alarm Can't Be Set", Toast.LENGTH_SHORT).show();
);
cancel.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
alertDialog.cancel();
);
break;
case R.id.select_date:
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String[] data = df.format(c.getTime()).split("-");
DatePickerDialog datePicker = new DatePickerDialog(this, onDate, Integer.parseInt(data[0]),
Integer.parseInt(data[1]), Integer.parseInt(data[2]));
datePicker.getDatePicker().setMinDate(System.currentTimeMillis());
datePicker.show();
break;
case R.id.select_time:
Calendar c1 = Calendar.getInstance();
TimePickerDialog timePicker=new TimePickerDialog(this, onTime, c1.get(Calendar.HOUR_OF_DAY), c1.get(Calendar.MINUTE), false);
timePicker.show();
break;
protected void setAlarm(String date, String time, String msg)
manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
alarmIntent.putExtra("date", ""+date);
alarmIntent.putExtra("time", ""+time);
alarmIntent.putExtra("msg", ""+msg);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
String[] data=time.split(":");
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt( data[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt( data[1]));
Log.d("calendar.getTimeInMillis()", ""+calendar.getTimeInMillis());
Log.d("System", ""+calendar.getTime());
manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "ALarm Set", Toast.LENGTH_SHORT).show();
OnDateSetListener onDate = new OnDateSetListener()
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
String month="";
if(monthOfYear<9)
month= "0"+String.valueOf(monthOfYear+1);
else
month=String.valueOf(monthOfYear+1);
tvDate.setText( pad(dayOfMonth)+ "-" + month+ "-" + String.valueOf(year));
;
OnTimeSetListener onTime= new OnTimeSetListener()
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
//tvTime.setText(pad(hourOfDay) + ":" + pad(minute));
;
private static String pad(int c)
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
private void addListDetails()
dbhelper=new DataBaseHelper(MainActivity.this);
AlarmAdapter adapter= new AlarmAdapter(MainActivity.this, dbhelper.getAlarmList());
adapter.notifyDataSetChanged();
alarmListView.setAdapter(adapter);
【讨论】:
我在 ListView 中使用 BaseAdapter ActionBarActivity 已弃用;请使用 AppCompatActivity以上是关于如何刷新片段上的列表视图的主要内容,如果未能解决你的问题,请参考以下文章
如何刷新其活动的 MenuitemSelected 上的片段?
片段中的 notifyDataSetChanged() 不刷新列表视图