[英]Android // Refresh a Custom Arrayadapter in a ListFragment from a Dialog
OK, the relevant things: OK,相关的事情:
I have a FragmentActivity (MainActivity.java)
which holds the references to a one Fragment (Tab1Fagment.java)
, and two ListFragments (Tab2- & Tab3Fragment.java)
. 我有一个FragmentActivity (MainActivity.java)
,其中包含对一个Fragment (Tab1Fagment.java)
和两个ListFragments (Tab2- & Tab3Fragment.java)
。 The Tab3Activity
is a ListFragment
which is created dynamically upon some dates which are read from the SharedSettings
. Tab3Activity
是一个ListFragment
,它是从SharedSettings
中读取的某些日期动态创建的。 Now, the dates are being set in a Dialog which is being launched from the Tab3Fragment . 现在,在从Tab3Fragment启动的对话框中设置日期。
Well, my question is - how do I refresh the list in the Tab3Fragment
when the dialog is dismissed? 好吧,我的问题是- Tab3Fragment
对话框后,如何刷新Tab3Fragment
的列表? - the onCreateView
method doesn't capture that event. onCreateView
方法不会捕获该事件。 The list is being refreshed if I switch to Tab1 and come back to Tab3 - but that's just a bad workaround. 如果我切换到Tab1,然后再回到Tab3,该列表将被刷新-但这只是一个不好的解决方法。
The relevant codes: 相关代码:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
//.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@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_activity_menu, menu);
menu.getItem(0).setVisible(menuShow);
return true;
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
DatePickerDialog datePickerDialog = new DatePickerDialog(this);
datePickerDialog.show(); //moram ici ovako jer mi trebaju listeneri za share dugme
getActionBar().selectTab(getActionBar().getTabAt(0));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0:
// Tab1 fragment activity
return new Tab1Fragment();
case 1:
// Tab2 fragment activity
return new Tab2Fragment();
case 2:
// Tab3 fragment activity
return new Tab3Fragment();
}
return null;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
//tab titles - not being used
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}}
Tab3Fragment.java Tab3Fragment.java
public class Tab3Fragment extends ListFragment {
SharedPreferences settings;
ListView listView;
String [][] TAB3QUESTIONS_REARRANGED;
String TAB3TITLES[], TAB3SUBTITLES[], TAB3ANSWERS[];
Date dateTAB3DATES[];
long longDateTAB3DATES[]; //needed to pass as Bundle to DetailsFragment, because Date[] cannot be passed, must be converted to long
Date currentDate;
long currentDateInMilliseconds, savedBirthDate, savedJaydessDate, savedLastCheckDate;
Calendar calendarCurrentDate, calenderSavedBirthDate, calenderSavedJaydessDate, calenderSavedLastCheckDate;
TextView textView1, textView2;
boolean bigCheckup;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//prepare file
settings = getActivity().getSharedPreferences("jaydess_shared_pref", 0);
//if dates were not found in the memory - display the date input dialog and a modified list
if (!((settings.contains("savedBirthDate")) && (settings.contains("savedJaydessDate")))) {
/*
//if TAB3 is selected show date input dialog
if (getActivity().getActionBar().getSelectedTab().getPosition() == 2) {
//there were no saved dates found -> fire the dates activity
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity());
datePickerDialog.show(); //moram ici ovako jer mi trebaju listeneri za share dugme
//getActivity().getActionBar().selectTab(getActivity().getActionBar().getTabAt(0));
}*/
TAB3TITLES = new String[1];
TAB3SUBTITLES = new String[1];
dateTAB3DATES = new Date[1];
longDateTAB3DATES = new long[1];
TAB3TITLES[0] = DataStructure.TAB3EXCEPTIONMESSAGE[0];
TAB3SUBTITLES[0] = DataStructure.TAB3EXCEPTIONMESSAGE[1];
}
else {
//initialize the variables and read saved data
initialize();
//run the titles, subtitles and answers arrangement procedure - THE TAB3 LOGIC
rearrange();
}
//load the arranged titles (main items)
ArrayAdapter<String> adapter = new MyArrayAdapter<String>(getActivity(), TAB3TITLES);
/** Setting the list adapter for the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
//needed for typeface setting in listFragments, see: http://stackoverflow.com/questions/14190648/change-font-of-list-fragment-on-detail-fragment
public class MyArrayAdapter<T> extends ArrayAdapter<T> {
public MyArrayAdapter(Context context, List<T> items) {
super(context, android.R.layout.simple_list_item_activated_2, android.R.id.text1, items);
}
public MyArrayAdapter(Context context, T[] items) {
super(context, android.R.layout.simple_list_item_activated_2, android.R.id.text1, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
textView1 = (TextView) view.findViewById(android.R.id.text1);
textView2 = (TextView) view.findViewById(android.R.id.text2);
textView1.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/BryantPro-Medium.otf"));
textView2.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/BryantPro-Light.otf"));
//set the subtitles
textView2.setText(TAB3SUBTITLES[position]);
//if dates exist (if saved and read)
if ((dateTAB3DATES[position] != null) && (currentDate != null)) {
//set the color of passed items to GRAY
if (dateTAB3DATES[position].before(currentDate)) {
textView1.setTextColor(Color.GRAY);
textView2.setTextColor(Color.GRAY);
}
else {
textView1.setTextColor(Color.BLACK);
textView2.setTextColor(Color.BLACK);
}
}
return view;
}
} /////// ETC.....
DatePickerDialog.java DatePickerDialog.java
this class basically just saves the dates to sharedpreferences and dismisses the dialog 此类基本上只是将日期保存到sharedpreferences并关闭对话框
saveData();
dismiss();
You can repopulate the ListView
on exiting the DatePickerDialog
by calling adapter.clear()
and adapter.addAll()
. 您可以通过调用adapter.clear()
和adapter.addAll()
在退出DatePickerDialog
重新填充ListView
。 Alternatively, you could delete/add specific elements, however if the number of elements is low just repopulate as it will produce less bugs and you won't notice any difference. 另外,您可以删除/添加特定的元素,但是,如果元素数量少,则只需重新填充,因为它将产生较少的错误,并且您不会注意到任何差异。
To create a Dialog
you can use this code inside the onCreate()
of Tab3Fragment
: 要创建一个Dialog
,可以在Tab3Fragment
的onCreate()
中使用以下代码:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Message")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// take any needed action
Tab3Fragment.this.updateData();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// take any needed action
Tab3Fragment.this.updateData();
}
});
Dialog dialog = builder.create();
You might want to add similar listener with setOnDismissListener
which is called if user presses 'back'. 您可能想使用setOnDismissListener
添加类似的侦听setOnDismissListener
,如果用户按下“后退”会调用该侦听器。
And in your Tab3Fragment
define method that will be called from the Dialog
: 然后在Tab3Fragment
定义将要从Dialog
调用的方法:
private void updateData(){
initialize();
rearrange();
}
Now when you want to show the dialog just call dialog.show()
. 现在,当您想显示对话框时,只需调用dialog.show()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.