2013-09-25 3 views
0

Я пишу простое приложение, которое открывает диалог выбора времени, запрашивает ввод, проверяет его на системное время и сообщает, правильно оно или нет. Тем не менее, мне нужно захватить TextView, который отображает, является ли он истинным или ложным, и изменить его в TimePickerFragment, который является диалоговым. Что мне делать?Что я хотел бы использовать для захвата TextView из MainActivity в диалоговом окне DialogFragment?

TimePickerFragment.java

package com.example.timechecker; 
import java.util.Calendar; 

import android.app.Dialog; 
import android.app.TimePickerDialog; 
import android.os.Bundle; 
import android.support.v4.app.DialogFragment; 
import android.text.format.DateFormat; 
import android.widget.TimePicker; 

public class TimePickerFragment extends DialogFragment 
         implements TimePickerDialog.OnTimeSetListener { 
int hour; 
int minutes; 


@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the current time as the default values for the picker 
    final Calendar c = Calendar.getInstance(); 
    hour = c.get(Calendar.HOUR_OF_DAY); 
    minutes = c.get(Calendar.MINUTE); 

    // Create a new instance of TimePickerDialog and return it 
    return new TimePickerDialog(getActivity(), this, 12, 00, 
      DateFormat.is24HourFormat(getActivity())); 
} 

public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 

    //Grab the Text View from the Main Activity 
//  MainActivity m = new MainActivity(); 
//  m.grabText text = new m.grabText(); 

    //Check if given Picker value is == to the system time, display whether or   not it is so 
    if (hourOfDay == hour && minutes == minute) { 
     text.setText("You are correct!"); 
    } else { 
     text.setText("You are incorrect!"); 
    } 
} 
} 

MainActivity.java

package com.example.timechecker; 

import android.os.Bundle; 
import android.support.v4.app.DialogFragment; 
import android.support.v4.app.FragmentActivity; 
import android.view.View; 
import android.widget.TextView; 

public class MainActivity extends FragmentActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 
//Creates the dialog with the Time Picker 
public void checkTime(View view) { 
    DialogFragment newFragment = new TimePickerFragment(); 
    newFragment.show(getSupportFragmentManager(), "timePicker"); 

} 

//Class to grab the Text View for the Dialog Fragment 
public class grabText { 
    TextView text = (TextView) findViewById(R.id.whatTime); 

    //Uses a method to set the Text View text 
    public void setText(String string) { 
     text.setText(string); 
    } 
} 

} 

ответ

0

При вызове findViewById в любой деятельности, то я только поиск в деятельности макете. поэтому, чтобы получить TextView из диалога, вам нужна ссылка на это диалоговое окно, а затем вы вызываете dialog.findViewById (id_of_field), и это даст вам желаемый TextView.

Надеется, что это помогает

+0

Ну, я пытаюсь захватить текстовое представление из основного действия, поэтому я могу изменить его с помощью переменных в классе TimePickerFragment –

0

Недавно я сделал это, я был в состоянии сделать это, делая MainActivity.java родитель моего DialogFragment.

MainActivity.Java

Добавьте к этому MainActivity:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    mActivity = this; 

После, сделать его глобальным здесь:

public class MainActivity extends Activity { 
    MainActivity mActivity; 

DialogFragment

Добавьте к этому DialogFragment:

public void setParent(MainActivity parent) { 
    mParent = parent; 
} 

После, сделать его глобальным здесь:

public class ClearDialogModern extends DialogFragment { 
    MainActivity mParent; 

EDIT: Вот где вы setParent. Поместите это в MainActivity.javaonCreate:

newDialogFragment = new DialogFragment(); 
newDialogFragment.setParent(mActivity); 

Как использовать:

Теперь вы можете использовать mParent ссылаться на MainActivity.java.

+0

Спасибо за помощь, хотя он говорит, что mParent не может быть разрешен к типу при попытке ' mParent.grabText text = new mParent.grabText(); ' –

+0

Обновленный ответ, я забыл установить родителя! :) –

 Смежные вопросы

  • Нет связанных вопросов^_^