如何通过Activity活动刷新Fragment的内容?

时间:2014-02-18 23:53:57

标签: java android android-fragments android-activity

我目前通过以下方式实现了SliderMenu及其自定义适配器: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

但是,我已将HomeFragment修改为有几个按钮,其中一个按钮创建一个自定义DialogBox。一旦出现Dialog,用户就会输入Project类的标题和描述,然后将其保存到HomeFragment中的ArrayList。此ArrayList中的对象使用此输入数据进行更新,但我的HomeFragment不显示输入数据。目前我正在尝试使用getFragmentManager()... Transition ... replace..commit例程并尝试了许多其他不成功的方法,它给了我一个NullPointerException。我是Android开发的新手,但我想找出一种方法将这些数据传递给我的MainActivity,然后让它显示一个新的HomeFragment视图,除了显示输入的新数据。

以下是MainActivity:

//package and imports...etc.


public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTitle=mDrawerTitle=getTitle();
    //load drawer menu items
    navMenuTitles=getResources().getStringArray(R.array.nav_drawer_items);
    //nav drawer icons from res
    navMenuIcons=getResources().obtainTypedArray(R.array.nav_drawer_icons);

    mDrawerLayout=(DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList=(ListView) findViewById(R.id.list_slidermenu);

    navDrawerItems=new ArrayList<NavDrawerItem>();

    //adding nav drawer items to array
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

    //RECYCLE
    navMenuIcons.recycle();
    //set the nav drawerlist adapter
    adapter=new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
    mDrawerList.setAdapter(adapter);
    //enable action bar app
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle=new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer,//nav menu toggle icon
            R.string.app_name,//nav drawer open - desc. for access
            R.string.app_name//nav drawer close - desc. for access      
    ){
        public void onDrawerClosed(View view){
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu();
        }
        public void onDrawerOpened(View drawerView){
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if(savedInstanceState==null){
        displayView(0);
    }

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

}


@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);

    MenuItem shareItem=(MenuItem) menu.findItem(R.id.action_share);
    ShareActionProvider mShare = (ShareActionProvider) shareItem.getActionProvider();
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    //shareIntent.putExtra(Intent.EXTRA_TEXT, "text to share");
    mShare.setShareIntent(shareIntent);

    return true;
}

public boolean onOptionsItemSelected(MenuItem item){
    if(mDrawerToggle.onOptionsItemSelected(item)){
        return true;
    }
    switch(item.getItemId()){
    case R.id.action_settings:
        return true;

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

//called when invalidateOptionsMenu() is triggered
@Override
public boolean onPrepareOptionsMenu(Menu menu){
    boolean drawerOpen=mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title){
    mTitle=title;
    getActionBar().setTitle(mTitle);
}
//using ActionBarDrawerToggle: call during onPostCreate() + onConfigurationChanged()
@Override
protected void onPostCreate(Bundle savedInstanceState){
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

private class SlideMenuClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        displayView(position);
    }
}

private void displayView(int position){
    Fragment fragment = null;
    switch(position){
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new ProjectsFragment();
        break;
    case 2:
        fragment = new PhotosFragment();
        break;
    case 3:
        fragment = new CommunityFragment();
        break;
    case 4:
        fragment = new PagesFragment();
        break;
    case 5:
        fragment = new InfoFragment();
        break;
    default:
        break;  
    }

    if(fragment != null){
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);     
    } else{
        Log.e("MainActivity", "Error in creating fragment");
    }
}

}

这是HomeFragment代码:

//package and imports...etc.

public class HomeFragment扩展了Fragment {

public ArrayList<Project> PL;
public ArrayList<Button> DB;
public ArrayList<TextView> TL;
public ArrayList<TextView> DL;
public Adapter adp;
public View rootView;
public HomeFragment(){
    PL=new ArrayList<Project>(3);
    DB=new ArrayList();
    TL=new ArrayList();
    DL=new ArrayList();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    rootView = inflater.inflate(R.layout.fragment_home, container, false);

    final Button newProjectButton = (Button) rootView.findViewById(R.id.new_project_button);
    DB.add((Button) rootView.findViewById(R.id.first_delete_button));
    DB.add((Button) rootView.findViewById(R.id.second_delete_button));
    DB.add((Button) rootView.findViewById(R.id.third_delete_button));
    DB.add((Button) rootView.findViewById(R.id.fourth_delete_button));
    TL.add((TextView) rootView.findViewById(R.id.first_tag_text));
    TL.add((TextView) rootView.findViewById(R.id.second_tag_text));
    TL.add((TextView) rootView.findViewById(R.id.third_tag_text));
    TL.add((TextView) rootView.findViewById(R.id.fourth_tag_text));
    DL.add((TextView) rootView.findViewById(R.id.first_desc_text));
    DL.add((TextView) rootView.findViewById(R.id.second_desc_text));
    DL.add((TextView) rootView.findViewById(R.id.third_desc_text));
    DL.add((TextView) rootView.findViewById(R.id.fourth_desc_text));

    newProjectButton.setOnClickListener(new View.OnClickListener(){
        int i=0;
        public void onClick(View v){
            if(i<4){
                PL.add(newProject(rootView));
                upText(i, PL.get(i).getTitle(), PL.get(i).getDesc());
            }
            i++;
        }
    }); 
    DB.get(0).setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            int i=0;
            Toast.makeText(getActivity(), "firstDelete: "+PL.get(0).getTitle(), Toast.LENGTH_LONG).show();
            /* Do delete stuff here */
        }
    });
    DB.get(1).setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            int i=0;
            Toast.makeText(getActivity(), "secondDelete: "+PL.get(1).getTitle(), Toast.LENGTH_LONG).show();
            /* do delete stuff here */
        }
    });
    DB.get(2).setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Toast.makeText(getActivity(), "thirdDelete"+PL.get(2).getTitle(), Toast.LENGTH_LONG).show();
            int i=0;
            /* do delete stuff here */
        }
    });
    DB.get(3).setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            Toast.makeText(getActivity(), "fourthDelete: "+PL.get(3).getTitle(), Toast.LENGTH_LONG).show();
            int i =0;
            /* do delete stuff here */
        }
    });

    return rootView;
}

public void upText(int loc, String title, String desc){
    TL.get(loc).setText(PL.get(loc).getTitle());
    DL.get(loc).setText(PL.get(loc).getDesc());
    Refresh();
}

protected void Refresh() {
    Fragment f = new HomeFragment();
    FragmentManager FM = getFragmentManager();
    FM.beginTransaction().replace(this.getId(), f).commit();        
}

public Project newProject(View view){
    //create localized Project
    final Project P=new Project();
    //create DialogBox
    final Dialog dialog = new Dialog(this.getActivity());
    //modify features BEFORE setting content view
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    dialog.setContentView(R.layout.project_dialog);
    //Create EditBoxes for Dialog
    final EditText titleEdit=(EditText) dialog.findViewById(R.id.dialog_title_text);
    final EditText descEdit=(EditText) dialog.findViewById(R.id.dialog_description_text);
    //define button's text
    TextView text=(TextView) dialog.findViewById(R.id.dialog_button_create);
    text.setText("Create");
    Button createButton = (Button) dialog.findViewById(R.id.dialog_button_create);
    // if button is clicked, close the custom dialog
    createButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            P.setTitle(titleEdit.getText().toString());
            P.setDesc(descEdit.getText().toString());
            Toast.makeText(getActivity(), "Create button: "+P.getTitle(), Toast.LENGTH_LONG).show();
            dialog.dismiss();
        }
    });

    dialog.show();
    return P;
}

}

修改

而不是使用:

        Fragment f = new HomeFragment();
    FragmentManager FM = getFragmentManager();
    FM.beginTransaction().replace(this.getId(), f).commit();

我现在正在尝试使用:

ListView list = (ListView) getActivity().findViewById(R.id.list_slidermenu);
    ((BaseAdapter)list.getAdapter()).notifyDataSetChanged();

这不会给我一个NullPointerException,但不会更新列表。

1 个答案:

答案 0 :(得分:1)

当您使用FragmentManager创建新事务时,您实际上是在抛弃现有片段,创建一个新片段,然后用现有片段替换新片段。当然,新的片段类不包含修改后的数据,因此会显示新的未修改数据。

看看这一行:

Fragment f = new HomeFragment();

你只是在创造一个全新的物体。

解除对话后,您根本不应执行任何片段事务,而只是更新现有片段的控件以反映新数据。