Pregunta

Hola, me preguntaba por qué la actualización del texto de un botón se comporta de manera diferente en mi aplicación.

Llamo a un fragmento que obtiene la información con la que se debe actualizar el botón, hago una devolución de llamada de interfaz desde el fragmento para actualizar una variable global que indica que la actividad actualiza el texto del botón.

El problema es que la actividad donde se encuentra el botón no actualiza el botón para mostrar el nuevo texto pero si lo hago a través del fragmento funciona, invalidar el botón no funciona ni forzar el refresco si lo hago a través de la actividad .

Aquí está la actividad que llama cuando presionas el botón, quien luego llama a un fragmento que muestra una lista y cuando haces clic en una opción, el botón debe cambiar su texto a lo que hayas elegido:

public void onClick_testSite(View view)
{
    // create the fragment
    SelectChartTypeDialogFragment chartType = new SelectChartTypeDialogFragment();
    // register you as a delegate for the callback
    chartType.delegate = this;
    // show the list
    chartType.show(getFragmentManager(), "WEE");

    // fetch the button and set the text ** DOESNT WORK **
    Button p1_button = (Button)findViewById(R.id.btn_pickChart);
    p1_button.setText(response);
    p1_button.invalidate();


}

@Override
public void processFinish(String response)
{
    this.response = response;
}

y aquí está parte del fragmento que maneja el diálogo:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    // get the list from a enum
    final List<ChartTypes> chartList = Arrays.asList(ChartTypes.values());
    // The array containing the different choices
    ArrayAdapter<ChartTypes> adapter = new ArrayAdapter<ChartTypes>(
            getActivity(), android.R.layout.simple_list_item_1, chartList);
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    // The dialog setting
    builder.setTitle(R.string.pick_chart);
    builder.setAdapter(adapter, new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int position)
        {
            // get the name of the enum based on the position, what one
            // clicked on the dialog
            String strName = chartList.get(position).name();

            // this sets the text in the activitys global variable
            delegate.processFinish(strName);
            // set the text in the fragment instead
            //changeBtnText(strName);

            //dialog.dismiss();
        }
    });

    // Create the AlertDialog object and return it
    return builder.create();
}

public void changeBtnText(String newBtnxt)
{
    Button button = (Button)getActivity().findViewById(R.id.btn_pickChart);
    button.setText(newBtnxt);
}

Mi pregunta es, ¿por qué actualiza el texto en la interfaz gráfica de usuario (cuando se ejecuta la aplicación) a través del fragmento pero no a través de la actividad, es decir, el método p1_button.setText(response);?

EDITAR respuesta como lo explica Raghunandan:El problema fue que no entendí eso. onClick_testSite(View view) completado incluso si no hizo clic en nada en el cuadro de diálogo, pensé que esperaba con la llamada de función de chartType.show() para que regrese y luego continúe hasta el final de la función.

¿Fue útil?

Solución

Necesitas inicializar public AsyncResponse delegate = null;

delegate =(AsyncResponse) getActivity();

Creo que este es el método implementado.

@Override
public void processFinish(String response)
{
     Log.i(".........",response); // check if the response is logged
     // if you get the response your button text will be changed
     // else you need to look at why the response is not logged.  
     p1_button.setText(response);
}

Declarar Button p1_button como variable de instancia (por ejemplo, antes de onCreate).

Inicializar esto

p1_button = (Button)findViewById(R.id.btn_pickChart); // in onCreate

Probablemente el botón se actualice incluso antes de recibir la respuesta en processFinish.Luego inicializas la variable de respuesta.Entonces, el texto del botón se establece la próxima vez que haga clic en el botón.

Puede declarar el botón antes de crear y actualizarlo en processFinish en lugar de hwon arriba.

Otros consejos

El ProcessFinish ahorra el valor a respuesta .Pero no solicita la vista de texto con btn_pickchart id.

Entonces, solo necesita guardar la instancia de TextView para la actividad:

private Button mP1Button;

protected void onCreate(Bundle savedInstanceState) {
...
    Button mP1Button = (Button) findViewById(R.id.btn_pickChart);
...
}

y aplicar el valor modificado cuando se llama strongfinish :

public void processFinish(String response) {
    this.response = response;
    // The value will be setup to the view element.
    mP1Button.setText(response);
}

Por la mejor manera no usar el delegado como campo.Puede usar la GetAactividad () o GetTargetfragment () para verificar la instancia de AsyncResponse y llamar al método ProcessFinish.

AsyncResponse asyncResponse = null;
if(getActivity() instanceof AsyncResponse) {
    asyncResponse = (AsyncResponse) getActivity();
} else if (getTargetFragment() instanceof AsyncResponse){
    asyncResponse = (AsyncResponse) getTargetFragment();
}

if(asyncResponse != null){
    asyncResponse.processFinish(strName);
}

Por cierto, no es necesario llamar al método invalidate después de SetText porque ya está llamado desde aquí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top