Domanda

Ciao Mi stavo chiedendo perché aggiornare il testo di un pulsante si comporta in modo diverso nella mia app.

Io chiamo un frammento che ottiene le informazioni con quale è necessario aggiornare il pulsante, eseguo un'interfaccia-callback dal frammento per aggiornare una variabile globale che l'attività aggiorna il testo del pulsante.

Il problema è che l'attività in cui si trova il pulsante non si aggiorna il pulsante per mostrare il nuovo testo, ma se lo faccio attraverso il frammento funziona, invalidando il pulsante non funziona o forza aggiornamento se lo faccio attraverso l'attività.

Ecco l'attività che chiama quando si preme il pulsante che chiama quindi un frammento che mostra un elenco e quando fai clic su un'opzione il pulsante dovrebbe cambiare il suo testo su qualsiasi cosa tu abbia scelto:

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;
}
.

Ed qui fa parte del frammento che gestisce la finestra di dialogo:

@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);
}
.

La mia domanda è, perché aggiorna il testo sulla GUI (quando si esegue l'app) attraverso il frammento ma non attraverso l'attività, I.e il metodo p1_button.settext (risposta);?

Modifica risposta come spiegato da Raghunanda: Il problema era che non ho capito che onClick_testSite(View view) completato anche se non hai fatto clic su nulla sulla finestra di dialogo, pensai che abbia aspettato con la funzione Call of chartType.show() per tornare e quindi procedere alla fine della funzione.

È stato utile?

Soluzione

È necessario inizializzare public AsyncResponse delegate = null;

delegate =(AsyncResponse) getActivity();
.

Credo che questo sia il metodo implementato

@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);
}
.

Dichiarare Button p1_button come variabile di istanza (ad esempio prima di OnCreate).

Inizializza questo

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

Probabilmente il pulsante viene aggiornato anche prima che la risposta venga ricevuta in processFinish.Quindi inizializza la variabile di risposta.Quindi il testo del pulsante è impostato la volta successiva, fai clic sul pulsante.

È possibile dichiarare il pulsante prima di oncreate e aggiornarlo in processFinish inveces hwon sopra.

Altri suggerimenti

Il ProcessFinish consente di risparmiare il valore su Risposta .Ma non è stato richiesto per TextView con BTN_PICKCHART ID.

Allora, devi solo salvare l'istanza di TextView per l'attività:

private Button mP1Button;

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

e applicare il valore modificato quando ProcessFinish è chiamato:

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

Per il modo migliore non usare il delegato come campo.È possibile utilizzare la Getactivity () o GetTatargeframment () per verificare l'installazione di AsyncResponse e chiamare il metodo 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);
}
.

A proposito, nessuna necessità di chiamare il metodo Invalidte dopo Setatext perché è già chiamato da qui.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top