从ActionBarActivity访问片段的变量

时间:2014-12-10 22:27:21

标签: java android android-fragments navigation-drawer android-fragmentactivity

我使用了结合Android Studio的示例来创建Android中的NavigationDrawer示例。我对代码做了一些小的修改,以便从主要活动中执行各种操作。

package ugr.mohabb.navigationdrawerexample;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**dsf* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private int sectionSelected;
    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {

        this.sectionSelected=position;
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment;
        switch(position){
            case 0:
                    fragment=new PlaceholderFragment("Section 1");
                    // I want to acces to variable Example, I try:
                    break;
            case 1:
                    fragment=new PlaceholderFragment("Section 2");
                    break;
            case 2:
                    fragment=new PlaceholderFragment( "Section 3");
                    break;
            default:
                    fragment=new PlaceholderFragment("Default");
                    break;

        }

        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
        private String Example;
        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment("Default");
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment( String Example) {
            this.Example=Example;
        }

        public String getExample() {
            return Example;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}

我修改了Fragment以将String作为参数合并到构造函数中。

 private String Example;
        public PlaceholderFragment( String Example) {
            this.Example=Example;
        }
在ActivityMain中,我添加了一个切换到不同的操作:

@Override
    public void onNavigationDrawerItemSelected(int position) {

        this.sectionSelected=position;
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment fragment;
        switch(position){
            case 0:
                    fragment=new PlaceholderFragment("Section 1");
                    // I want to acces to variable Example??
                    break;
            case 1:
                    fragment=new PlaceholderFragment("Section 2");
                    break;
            case 2:
                    fragment=new PlaceholderFragment( "Section 3");
                    break;
            default:
                    fragment=new PlaceholderFragment("Default");
                    break;

        }

        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
    }

我的问题是,如何从活动中访问Fragment扩展类的方法和变量?

谢谢,

2 个答案:

答案 0 :(得分:0)

当用户从导航栏中选择列表项时,我们需要在主视图中显示所需的视图。这可以通过添加列表项单击侦听器并在回调事件中加载受尊重的片段视图来完成。

示例代码:

public class MainActivity extends Activity {
..
..
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    ..
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

     /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

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

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
}

有关详细信息,请参阅here

答案 1 :(得分:0)

在你的片段中,声明接口......

public interface OnDataPass {
    public void onDataPass(String data);
}

然后,将接口的包含类实现连接到onAttach方法中的片段,如下所示:

OnDataPass dataPasser;

@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    dataPasser = (OnDataPass) a;
}

在你的片段中,当你需要处理数据传递时,只需在dataPasser对象上调用它:

public void passData(String data) {
    dataPasser.onDataPass(data);
}

最后,在实现OnDataPass ...的包含活动中

@Override
public void onDataPass(String data) {
    Log.d("LOG","hello " + data); // or whatever
}