2014. 9. 29. 19:39
프로그래밍/Android
가끔 액티비티가 아닌 다른 클래스에서 액티비티를 컨트롤 하고 싶을 때가 있습니다. 그럴땐 아래와 같은식으로 처리해주시면 됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { Button button1, button2; TextView textView1; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); textView1 = (TextView) findViewById(R.id.textView1); ClickAdapter clickAdapter = new ClickAdapter( this ); button1.setOnClickListener(clickAdapter); button2.setOnClickListener(clickAdapter); } } |
위와 같이 다른 클래스로 Context를 넘기시면 되구요.
ClickAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import android.content.Context; import android.view.View; public class ClickAdapter implements View.OnClickListener{ Context mContext; public ClickAdapter(Context context){ mContext = context; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button1: this .showText(); break ; case R.id.button2: this .hideText(); break ; } } private void hideText() { ((MainActivity) mContext).textView1.setVisibility(View.INVISIBLE); } private void showText() { ((MainActivity) mContext).textView1.setVisibility(View.VISIBLE); } } |
액티비티를 컨트롤하는 클래스에서 생성자에서 Context를 받은 뒤 위의 코드와 같이 처리해주시면 됩니다. 혹시나 궁금하신 분이 있을까 해서 정리겸 올립니다.