Abhay Kumar
Abhay Kumar

Reputation: 1618

Android objects accessible globally in the class

how to i make a object of views buttons textviews globally accessible in the activity... i have used the below code but its now working..

 private View dummy = (View) View.inflate(this, R.layout.main, null);
 private TextView p1 = (TextView)dummy.findViewById(R.id.player1other);
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(dummy);
 }
 .....
 .....
  public OnClickListener mCorkyListener = new OnClickListener() {

        @Override
    public void onClick(View v) {

        switch(v.getId())
        {
        case R.id.player1:      
        p1.setText(Integer.toString(scores.scores[0])); 

                       break;     }}

Upvotes: 1

Views: 127

Answers (5)

Kristiono Setyadi
Kristiono Setyadi

Reputation: 5643

Try this:

private TextView p1;

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

    p1 = (TextView) findViewById(R.id.player1other);
}

and the rest is just the same.

Upvotes: 0

Sarmad
Sarmad

Reputation: 389

You cannot give reference of Activity before its initiation. You can do your desired work in this way

private View dummy;
 private TextView p1;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(dummy);
        dummy = (View) View.inflate(this, R.layout.main, null);
        p1 = (TextView)dummy.findViewById(R.id.player1other);
 }
 .....
 .....
  public OnClickListener mCorkyListener = new OnClickListener() {

        @Override
    public void onClick(View v) {

        switch(v.getId())
        {
        case R.id.player1:      
        p1.setText(Integer.toString(scores.scores[0])); 

                       break;     }}

Upvotes: 1

success_anil
success_anil

Reputation: 3658

Rather than using this line ....

private View dummy = (View) View.inflate(this, R.layout.main, null); 

Use this

LayoutInflater l1 = this.getLayoutInflater();
private View dummy = l1.inflate(R.layout.main, null); 

Upvotes: 0

Ognyan
Ognyan

Reputation: 13600

You need first to call setContentView() before using findViewByID() in order findViewByID() to know where to look for the views. Like this:

private TextView p1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    p1 = (TextView)dummy.findViewById(R.id.player1other);
}

i.e. first just declare p1, then call appropriate setContentView() in onCreate(), then initialize p1.

Upvotes: 0

Rasel
Rasel

Reputation: 15477

Declare your views as class variable

Class A{
EditText edit1;

}

edit1 will be accessible anywhere in the class

Upvotes: 0

Related Questions