Android //从对话框中刷新ListFragment中的自定义Arrayadapter

时间:2014-02-25 22:05:47

标签: android dialog android-arrayadapter android-listfragment

好的,相关的事情:

我有一个FragmentActivity (MainActivity.java),其中包含一个Fragment (Tab1Fagment.java)和两个ListFragments (Tab2- & Tab3Fragment.java)的引用。 Tab3ActivityListFragment,它是在SharedSettings读取的某些日期动态创建的。现在,日期正在从Tab3Fragment 启动的对话框中设置。

好吧,我的问题是 - 当对话框被解除时,如何刷新Tab3Fragment中的列表? - onCreateView方法不捕获该事件。如果我切换到Tab1并返回到Tab3,则列表正在刷新 - 但这只是一个糟糕的解决方法。

相关代码:

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

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

这个类基本上只是将日期保存到共享偏好并解除对话框

            saveData();
        dismiss();

1 个答案:

答案 0 :(得分:0)

通过致电adapter.clear()adapter.addAll(),您可以在退出ListView时重新填充DatePickerDialog。或者,你可以删除/添加特定的元素,但是如果元素的数量很少,只需重新填充,因为它会产生更少的错误,你不会发现任何差异。

要创建Dialog,您可以在onCreate()的{​​{1}}内使用此代码:

Tab3Fragment

如果用户按下“后退”,您可能希望添加类似于setOnDismissListener的侦听器。

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(); 定义的方法中,将从Tab3Fragment

调用
Dialog

现在,当您想要显示对话框时,只需致电private void updateData(){ initialize(); rearrange(); }