glass
glass

Reputation: 179

findViewById from a different class

This should be simple, but even reading other solutions I can't get it... I simply want to access a TextView with findViewById from a different class (it's in a different file), how to do that?

MainActivity:

public class MainActivity extends ActionBarActivity {

    private TextView label0 = (TextView) findViewById(R.id.label0);
    MyDialog d = new MyDialog(this);

    public MainActivity(){

    }

    //other methods and stuff...
}

Here is the DialogFragment that must access the TextView:

public class MyDialog extends DialogFragment {

    private Activity MainActivity;
    private TextView label0;

    public MyDialog(Activity parent) {
    this.MainActivity = parent;
    }

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.alert_content)
           .setPositiveButton(R.string.alert_button, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

               //here it is, trying to access label0. This is one of the many tries
               label0 = MainActivity.findViewById(R.id.label0);

               //do other stuff...
}

I also read many times to never make the views "public static", Is that right?

Upvotes: 0

Views: 383

Answers (2)

Nazgul
Nazgul

Reputation: 1902

save the textview as a private property of activity and expose it as getters for fragment. Thats the standard way to do it. You will need to cast fragment.getActivity() to your activity type and then access the textviewas a getter.

Edit---------------- in the main activity you already have private TextView label0 just fill its value in onCreateView. Then provide a getter method in your activity to access this textView from outside the activity.

public TextView getLabelTextView(){
    return this.label0;
}

Now in your fragment do something like this:

Activity activity = this.getActivity();
MainActivity myActivity = (MainActivity)activity;
TextView tv = myMactivity.getLabelTextView();

And you should be good to go.

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

  1. There is no need for constructor for Activity class.

  2. Fragments must have no arg constructor

  3. The below in Activity is wrong

    private TextView label0 = (TextView) findViewById(R.id.label0); MyDialog d = new MyDialog(this);

  4. The fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout. Read Communicating with activity @ developer.android.com/guide/components/fragments.html

Upvotes: 1

Related Questions