1

So, suppose I have an array x:

String x[][] = {
       {"First item", "meti tsriF"},
       {"Second", "dnoceS"},
       //ect. ect.
};

And I have two TextViews in my .xml file, alpha and beta.

In my method is as follows:

public void Liszt(){
    TextView beta = (TextView) findViewById(R.id.beta);
    TextView alpha = (TextView) findViewById(R.id.alpha);

    alpha.setTextSize(22);
    beta.setTextSize(22);

    for(int t=0;t<x.length;t++) {
            alpha.append(x[t][1] + "\n");
    }

    for(int t=0;t<x.length;t++) {
            beta.append(x[t][1] + "\n");
    }

This method is located in the "MainActivity" class and the .xml file is displayed when I call upon its fragment. So, how could I call this method when I call the fragment? Could I just add "MainActivity.Liszt()" in the "onCreate" method?

CreedVI
  • 129
  • 11
  • Is there an issue with just passing in `x` when you initialize the fragment? – tachyonflux Dec 24 '14 at 02:06
  • My issue is I need to run that method when I load a fragment, so when alpha and beta are displayed they are filled with the content from x – CreedVI Dec 24 '14 at 02:10
  • Right, that doesn't answer my question. Why can't your method be in your fragment class and you just pass in the data from the MainActivity. alpha and beta are in your fragment layout, correct? – tachyonflux Dec 24 '14 at 02:14
  • http://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment/9245510#9245510 – tachyonflux Dec 24 '14 at 02:20
  • You are correct alpha and beta are in the fragment layout. However, the problem I run into when I have "Liszt" in the fragment class is Android Studio cannot resolve the method "findViewById" and I did not want to move the over 100 line array since it is already being used in the MainActivity. @tachyonflux – CreedVI Dec 24 '14 at 02:20
  • There's no problem with moving the array, you're just passing a reference to it. – tachyonflux Dec 24 '14 at 02:26

2 Answers2

0

create your references in onActivityCreated.

public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        beta = (TextView) getView().findViewById(R.id.beta);
        alpha = (TextView) getView().findViewById(R.id.alpha);
}
tachyonflux
  • 20,103
  • 7
  • 48
  • 67
  • No, you were saying that you cannot resolve the method `findViewById`. This is how you are suppose to do it for a fragment. – tachyonflux Dec 24 '14 at 03:21
0

Your code run correctly if the MainActivity must contain the fragment that you want to call Liszt method. In fragment class you can call any method using view properties. However, I suggest you should define the interface which has Liszt() method, then the MainActivity implements this interface. Finally, you can call the Liszt method through instance of interface. I think this is a great way to do it.

Dat Nguyen
  • 1,881
  • 17
  • 36