Dave Martin
Dave Martin

Reputation: 1407

pass UI Controls from activity to a class

I stuck at this issue many times and I passed the problem in different ways and I'm not sure that I made it in the right way. I simplified the problem in a the following example. I know that I can pass only the data to the class but I do want to pass the editText cause I have this problem with more difficult UI controls.

mainactivity.java

public class mainactivity extends Activity {

    public EditText clickEditText;
    int count =0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        newTxt();
    }

    public void newTxt() {
        txt = new MyText(context);
        txt.updateTextEdit("Main Activity");
    }
}

myText.java

public class MyText
{
    private Context _context;

    // constructor
    public MyText(Context context) 
    {
        _context = context;
    }

    public void updateTextEdit(String str)
    {
        private EditText strEditText;
        strEditText= (EditText)findViewById(_context.R.id.editTextClick); // ????
        strEditText.setText(str + " and myTxt");
    }
} 

if you could explain me how to fix the updateTextEdit function. i passed the context of the main activity. How can I change the editText? Thank you very much!!!

Upvotes: 4

Views: 1216

Answers (2)

La bla bla
La bla bla

Reputation: 8708

There's a similar question here How to access Activity UI from my class?

You didn't say how you obtained the context, you should use this and get the mainactivity in the other class. not context.

then you can call runOnUIThread to perform UI updates.

Upvotes: 0

David Wasser
David Wasser

Reputation: 95578

If you really want to do this this way, you need to save a reference to Activity, not Context. Like this:

public class MyText
{
    private Activity _activity;

    // constructor
    public MyText(Activity activity) 
    {
        _activity= activity;
    }

    public void updateTextEdit(String str)
    {
        private EditText strEditText;
        strEditText= (EditText)activity.findViewById(R.id.editTextClick);
        strEditText.setText(str + " and myTxt");
    }
}

and in newTxt() you will need to change:

txt = new MyText(context);

to:

txt = new MyText(this);

But wouldn't it be easier to just put this method inside your activity? Why do you want it in another class? If it really needs to be in another class, you could make that class an inner class of your activity and you would still have access to the activity's methods and member variables.

Upvotes: 1

Related Questions