user2341387
user2341387

Reputation: 303

Android: OnClickListener OnClick event in different class

I want to set OnClick event inside another class that can be used by 2 different class (Activity A and Activity B)

Example:

Activity A

public class A extends Activity {

    String sample = "Sample text";

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

        TextView textview = (TextView) findViewById (R.id.textview);
        findViewById(R.id.btn_sampleA).setOnClickListener(new C());

    }
}

Activity B

public class B extends Activity {

    String sample = "Sample text";

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

        TextView textview = (TextView) findViewById (R.id.textview);
        findViewById(R.id.btn_sampleB).setOnClickListener(new C());

    }
}

Activity C where onClick event placed

public class C implements OnClickListener {

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.btn_sampleA:
            textview.setText(sample);
            break;
        case R.id.btn_sampleB:
            textview.setText(sample);
            break;
    }
}

Tried by myself but not working, so is that possible doing like that? Or there's another way that can be used?

Upvotes: 0

Views: 987

Answers (1)

FD_
FD_

Reputation: 12919

Change the constructor of class C to take a TextView as an argument:

public class C implements OnClickListener {
TextView mTextView;    

public C (TextView text){
    mTextView = text;
}

@Override
public void onClick(View v) {
    switch(v.getId()) {
    case R.id.btn_sampleA:
        mTextView.setText(sample);
        break;
    case R.id.btn_sampleB:
        mTextView.setText(sample);
        break;
}
}

Then call instantiate C like this:

findViewById(R.id.btn_sampleA).setOnClickListener(new C(textView));

Upvotes: 3

Related Questions