2012-05-07 3 views
0

날짜/시간 구성 요소를 만들었지 만 자동으로 생성되었습니다 (XML 레이아웃으로 만들었으므로 수동으로 생성하고 싶지는 않습니다).하지만 참조를 대화 상자를 만들려면 Activity. 어떻게하면 될까요? 내가 findViewById 후 세터를 시도했지만이 좋은 해결책이 아니다 ...액티비티 참조를 내 구성 요소에 전달하는 방법

public class DateTimeComponent extends RelativeLayout { 

    private Activity activity; 

    public DateComponent(Context context, AttributeSet attributeSet) { 
     super(context, attributeSet); 
     // rest ommited 
     initFields(); 
    } 

    private void initFields() { 
     dateEditText = (EditText) findViewById(R.id.dateEditText); 
     dateEditText.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       activity.showDialog(DATE_PICKER_DIALOG); 
      } 
     }); 

     timeEditText = (EditText) findViewById(R.id.timeEditText); 
     timeEditText.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       activity.showDialog(TIME_PICKER_DIALOG); 
      } 
     }); 
    } 

    // rest ommited 

    public Dialog getDatePickerDialog() { 
     int year = selectedDateTime.get(YEAR); 
     int month = selectedDateTime.get(MONTH); 
     int day = selectedDateTime.get(DAY_OF_MONTH); 
     return new DatePickerDialog(activity, onDateSetListener, year, month, day); 
    } 

    public Dialog getTimePickerDialog() { 
     int hour = selectedDateTime.get(HOUR_OF_DAY); 
     int minute = selectedDateTime.get(MINUTE); 
     return new TimePickerDialog(activity, onTimeSetListener, hour, minute, true); 
    } 

    private final OnDateSetListener onDateSetListener = new OnDateSetListener() { 
     @Override 
     public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
      // do something 
     } 
    }; 

    private final OnTimeSetListener onTimeSetListener = new OnTimeSetListener() { 
     @Override 
     public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
      // do something 
     } 
    }; 

} 
+0

생성자를 통해 Activity/Context의 참조를 DateTimeComponent로 전달할 수 있습니다. – adatapost

+0

이 목적을 위해 컨텍스트를 사용할 수 있습니다. – Akram

+0

@Akki 컨텍스트에는'showDialog()'메서드가 없습니다 .. – user219882

답변

1

는 아마도이 당신을 도울 수 있습니다

옵션 1 :

public class DateTimeComponent extends RelativeLayout { 
    private Activity activity; 

    public DateTimeComponent(Activity act){ 
     activity = act; 
    } 

    public void someListener() { 
     activity.showDialog(...); 
    } 

} 

옵션 2 :

public class DateTimeComponent extends RelativeLayout { 

    public void someListener(Activity act) { 
     act.showDialog(...); 
    } 

} 

옵션 3 :

... 
    private Activity activity; 

    public DateComponent(Context context, AttributeSet attributeSet) { 
     super(context, attributeSet); 

     activity = (Activity) getContext(); 

     // rest ommited 
     initFields(); 
    } 

... 
+0

하지만 구성 요소를 만들지 않고'DateComponent component = (DateComponent) findViewById (R.id.dateComponent)' – user219882

+0

업데이트 된 답변보기 – waqaslam

+0

내 질문이 업데이트되었습니다. 두 번째 옵션은 구성 요소 자체의 모든 수신기를 초기화하기 때문에 사용할 수 없습니다. – user219882

1

두 가지 방법 -

  1. 이 컨텍스트 매개 변수를 허용하는 생성자를 작성, 당신은 할 때마다 사용할 수있는 Context 형의 (개인?) 클래스 변수가 있습니다.

  2. 필요한 모든 메소드에 대한 추가 컨텍스트 컨텍스트 매개 변수를 추가하십시오. 경우에 따라 최종 결정을해야 할 수도 있습니다.

1

생성자가받는 컨텍스트는 활동입니다. 그래서, 당신은 그것을 캐스팅 할 수 있습니다. 예 : this like

MyActivity a = (MyActivity) getContext(); 

P.S. 이미 내부에 저장되고 http://developer.android.com/reference/android/view/View.html#getContext()

증거

사용자 정의 텍스트보기에 의해 얻을 수

private Activity activity; // not needed 

:

당신은 자신의 분야에서 활동을 저장할 필요가 없습니다
public class MyTextView extends TextView { 

public MyTextView(Context context) { 
    super(context); 
    setText(Integer.toString(System.identityHashCode(context))); 
} 

public MyTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    setText(Integer.toString(System.identityHashCode(context))); 
} 


} 

활동 :

public class ContextActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    TextView textView = (TextView) findViewById(R.id.textView); 

    textView.setText(Integer.toString(System.identityHashCode(this))); 
} 
} 

레이아웃 : 미리 보여줍니다

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView" /> 

<com.inthemoon.incubation.MyTextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 

</LinearLayout> 

코드는 동일하다.

+0

궁금합니다. '생성자가받는 컨텍스트는 액티비티입니다.' – MByD

+0

'Activity' 클래스는'Context'의 자손입니다. 나는 실험적으로 결정했다. 그 활동은 설명 된 것과 같은 간단한 경우에 생성자에게 전달된다. 나는 초보자이며 항상 그렇게 보장 할 수는 없습니다. 'Context'는 여러 구현을 가지고 있으므로 어떤 경우에는 사용할 수 있습니다. –

+0

이것은 증거가 아닙니다. ** 현재 플랫폼 **의 ** 현재 ** 구현임을 보여줍니다. – MByD

관련 문제