eclipse 从另一个片段调用一个片段中的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27217362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 22:15:41  来源:igfitidea点击:

Calling a method in one fragment from another

javaandroideclipselistviewfragment

提问by K Manos

I've been trying for a while already (as well, searching in here) for something to help me to refresh listView in my MainFragment, when a button is pressed in other fragment. Could sommeone explain me how to make it work?

我已经尝试了一段时间(也在此处搜索)以帮助我在其他片段中按下按钮时刷新 MainFragment 中的 listView。有人可以解释我如何使它工作吗?

Here's MainFragment with the function (I excluded other functions, since I don't see how they contribute):

这是带有函数的 MainFragment(我排除了其他函数,因为我看不到它们是如何贡献的):

public class MainFragment extends Fragment {
public void otherList() {
    SQLite db = new SQLite(getActivity());
    db.open();
    Calendar sCalendar = Calendar.getInstance();
    String day = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK,
            Calendar.LONG, Locale.ENGLISH);
    Cursor c = db.getAllRecords(day);
    Calendar cal = Calendar.getInstance();
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    arrayOfBars.clear();
    if (c.moveToFirst()) {
        do {
            String country = c.getString(0);
            String city = c.getString(1);
            String bar = c.getString(2);
            String timeStart = c.getString(3);

            String[] h = timeStart.split(":");
            int times = Integer.parseInt(h[0]);

            String timeEnd = c.getString(4);
            String[] h2 = timeEnd.split(":");
            int timee = Integer.parseInt(h2[0]);

            String placeLaLo = c.getString(5);
            String description = c.getString(6);
            String likes = c.getString(7);
            String offer = c.getString(8);

            if (hour < (times + 1) || hour < (timee)) {
                getPrefs = PreferenceManager
                        .getDefaultSharedPreferences(MainFragment.this
                                .getActivity());
                boolean lay = getPrefs.getBoolean("boolean", false);
                if (lay == true) {
                    while (times < timee) {
                        timeStart = times + ":" + h[1];
                        times++;
                        timeEnd = times + ":" + h2[1];
                        arrayOfBars.add(new BarObject(country, city, bar,
                                timeStart, timeEnd, placeLaLo, description,
                                likes, offer, bar));
                    }
                } else {
                    arrayOfBars.add(new BarObject(country, city, bar,
                            timeStart, timeEnd, placeLaLo, description,
                            likes, offer, bar));
                }
            }

        } while (c.moveToNext());

        Collections.sort(arrayOfBars, new BarObject.CompST());

        lv2.setAdapter(null);
        adapter = new BarAdapter(getActivity(), arrayOfBars);
        lv2.setAdapter(adapter);
    } else {
        Toast.makeText(getActivity(), "No database found",
                Toast.LENGTH_LONG).show();
    }
    db.close();
}

}

}

And here's the other fragment:

这是另一个片段:

public class SocialMedia extends Fragment {
ImageButton facebook, twitter, layoutS;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.social_media, container, false);
    layoutS = (ImageButton) view.findViewById(R.id.ibLayout);

    layoutS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences getPrefs = PreferenceManager
                    .getDefaultSharedPreferences(SocialMedia.this
                            .getActivity());
            boolean lay = getPrefs.getBoolean("boolean", false);
            SharedPreferences.Editor e = getPrefs.edit();
            lay = !lay;
            e.putBoolean("boolean", lay);
            e.commit();
                            //Here I want to call otherList() from MainFragment
        }
    });
    return view;
}

}

}

回答by K Manos

FragmentManager fm = getFragmentManager(); 
MainFragment fragm = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
fragm.otherList(); 

This code worked best for me. And seems quite easy

这段代码最适合我。而且看起来很容易

回答by Rakesh Kumar

In MainFragment class you can do the following code:

在 MainFragment 类中,您可以执行以下代码:

private static MainFragment instance = null;

@Override  
public void onCreate(@Nullable Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    instance = this;  
}

public static MainFragment getInstance() {  
    return instance;  
} 

And in SocialMedia class you can call the method as follows:

在 SocialMedia 类中,您可以按如下方式调用该方法:

MainFragment.getInstance().otherList();   

回答by Mohammad Rahchamani

you should use interfacefor this. define an interfacein OtherFragmentclass and implement that in your MainActivityand define a publicmethod in your MainFragmentfor refreshing your ListViewand call that method from your MainActivity. here is an example :

你应该interface为此使用。定义一个interfaceinOtherFragment类并在您的类中实现它并在您的类中MainActivity定义一个public方法MainFragment以刷新您ListView并从您的MainActivity. 这是一个例子:

public Class OtherFragment extends Fragment implements OnClickListener {

private Communicator communicator;

   ...

public void setCommunicator(Communicator communicator) {
    this.communicator = communicator;
}

@Override
public void onClick(View v) {
   communicator.clicked();
}

   public interface Communicator {
      public void clicked();
   }
}

and in your MainActivity:

并在您的MainActivity

public class MainActivity extends Activity implements OtherFragment.Communicator {

   MainFragment mainFragment;

   @Override
   protected void onCreate(Bundle b) {
      ...
      OtherFragment otherFragment = new OtherFragment();
      otherFragment.setCommunicator(this);
      ...
   }

   ...

   @Override 
   public void clicked() {
     mainFragment.updateList();
   }
}

and in your MainFragment:

并在您的MainFragment

public class MainFragment extends Fragment {

    ...

    public void updateList() {
        // update list
    }
}

回答by m0skit0

To call a method from another object (a Fragment is an object) you need to have the reference of that object. So if you want to call MainFragment#otherList()from a SocialMediainstance, SocialMedianeeds a reference to MainFragment.

要从另一个对象(Fragment 是一个对象)调用方法,您需要拥有该对象的引用。所以如果你想MainFragment#otherList()从一个SocialMedia实例调用,SocialMedia需要一个对MainFragment.

For example:

例如:

public class SocialMedia {

    private MainFragment mainFragment = null;

    public void setMainFragment(final MainFragment mainFragment) {
        this.mainFragment = mainFragment
    }
}

Then you can use this.mainFragment.otherList().

然后你可以使用this.mainFragment.otherList().

回答by Sanjeev Kumar

            // Calling Parent Fragment method from Child Fragment.
        // Child Fragment
        AppCompatActivity activity = (AppCompatActivity) view.getContext();
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        NavigateFragment navigateFragment = (NavigateFragment) fragmentManager.findFragmentById(R.id.fragment_place_dashboard);
        navigateFragment.sayHelloWorld();


        // -- Some method in Parent Fragment(NavigateFragment).
        public void sayHelloWorld(){
            Log.d(TAG, "Hello World.");
        }