2013-08-28 5 views
7

Sto lavorando con ViewPager con 3 Fragments e voglio cambiare il testo di TextView nella terza pagina.Ottieni ID di TextView in Fragment da FragmentActivity in ViewPager

In quella pagina ho uno Button che quando viene premuto, andare su immagini SD per selezionarne uno. Al termine, torna alla pagina e si desidera aggiornare TextView con il percorso di quell'immagine. Il problema è che quando provo ad accedere a quello TextView da FragmentActivity è nullo.

Ecco il mio codice

SherlockFragmentActivity:

public class TabsFacturasActivity extends SherlockFragmentActivity { 

    protected MyApplication myApplication; 
    private static final int FILE_SELECT_CODE = 0; 

    private MyAdapter mAdapter; 
    private ViewPager mPager; 
    private PageIndicator mIndicator; 
    private TextView textViewImg; 

    private int lecturas = 0; 
    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
    private boolean adjunto = false; 
    private String filePath; 
    private boolean esLecturaAT = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.fragment_pager); 

     // Get the application instance 
     myApplication = (MyApplication)getApplication(); 

     //Need to get that view 
     textViewImg = (TextView) findViewById(R.id.textViewUrlImgLectura); 

     //Creamos la lista 
     LinkedList<String> direcciones = new LinkedList<String>(); 
     ArrayList<TuplaCupsWS> dirs = myApplication.getUsuarioActual().getCups(); 
     for(int dir = 0; dir < myApplication.getUsuarioActual().getCups().size(); dir++) { 
      direcciones.add(new String(dirs.get(dir).getDireccion())); 
     } 

     int tab = getIntent().getIntExtra("tab", 0); 

     mAdapter = new MyAdapter(getSupportFragmentManager()); 

     mPager = (ViewPager)findViewById(R.id.pager); 
     mPager.setAdapter(mAdapter); 
     mPager.setCurrentItem(tab); 

     mIndicator = (TitlePageIndicator)findViewById(R.id.indicator); 
     mIndicator.setViewPager(mPager); 

     getSupportActionBar().setDisplayShowTitleEnabled(false); 
     getSupportActionBar().setIcon(R.drawable.logo_factorenergia_peque); 

     /** Create an array adapter to populate dropdownlist */ 
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(
       getBaseContext(), android.R.layout.simple_spinner_dropdown_item, direcciones); 

     /** Enabling dropdown list navigation for the action bar */ 
     getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 

     /** Defining Navigation listener */ 
     OnNavigationListener navigationListener = new OnNavigationListener() { 

      @Override 
      public boolean onNavigationItemSelected(int itemPosition, long itemId) { 
       return false; 
      } 
     }; 

     /** Setting dropdown items and item navigation listener for the actionbar */ 
     getSupportActionBar().setListNavigationCallbacks(adapter, 
       (com.actionbarsherlock.app.ActionBar.OnNavigationListener) 
       navigationListener); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch (requestCode) { 
      case FILE_SELECT_CODE: 
      if (resultCode == RESULT_OK) { 
       adjunto = true; 
       // Get the Uri of the selected file 
       Uri uri = data.getData(); 
       // Get the path 
       String path = ""; 
       try { 
        path = MyUtility.getPath(this, uri); 
       } catch (URISyntaxException e) { 
        myApplication.throwException(this); 
        e.printStackTrace(); 
       } 
       String imgName = path.split("/")[path.split("/").length-1]; 
       textViewImg.setText(imgName); //Here textViewImg is null 
       filePath = path; 
      } 
      break; 
     } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 

    //Method executed when Button is pressed 
    public void examinar(View view) { 
     mostrarFileChooser();  
    } 

    private void mostrarFileChooser() {  
     Intent intent = new Intent(Intent.ACTION_PICK); 
     intent.setType("image/*"); 

     try { 
      startActivityForResult(intent, FILE_SELECT_CODE); 
     } catch (android.content.ActivityNotFoundException ex) { 
     } 
    } 

    private static class MyAdapter extends FragmentPagerAdapter { 

     private String[] titles = { "VER FACTURAS", "VER CONSUMO", "INTRODUCIR LECTURA" }; 

     public MyAdapter(FragmentManager fragmentManager) { 
      super(fragmentManager); 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      return titles[position]; 
     } 

     @Override 
     public Fragment getItem(int position) { 
      switch (position) { 
      case 0: // Fragment # 0 
       return new FacturasActivity(); 
      case 1: // Fragment # 1 
       return new ConsumoActivity(); 
      case 2:// Fragment # 2 
       return new LecturaActivity(); 
      } 
      //return new MyFragment(); 
      return null; 
     } 

     @Override 
     public int getCount() { 
      return titles.length; 
     } 
    } 

} 

fragment_pager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    tools:context=".TabsFacturasActivity" > 

    <com.viewpagerindicator.TitlePageIndicator 
     android:id="@+id/indicator" 
     android:padding="10dip" 
     android:layout_height="wrap_content" 
     android:layout_width="fill_parent" /> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/pager" 
     android:layout_width="fill_parent" 
     android:layout_height="0dp" 
     android:layout_weight="1" 
     android:background="#1184A4E8" /> 

</LinearLayout> 
+1

dove è textViewImg dichiarato? –

+0

se si ha la visualizzazione di testo in 'fragment_pager', quindi è possibile inizializzarlo con' findViewById'. – Raghunandan

+0

Mi dispiace, l'ho dimenticato. È dichiarato in xml di 'LecturaActivity' (terza pagina), quindi non è in' fragment_pager'. – Lyd

risposta

12

cant testo vista l'accesso da fragment activity perché la sua Situato sulla fragment e il tuo fragment activity layout non hanno alcun text view con questo id. Devi accedere alla visualizzazione del testo dal tuo third fragment dove lo hai usato nel suo layout. Quindi accedi a tale object dal tuo fragment activity.

nel frammento fare qualcosa di simile

TextView mTextView; 
mTextView = (TextView)getView().findViewById(R.id.your_text_view); 

Creare una funzione come questa

public void changeText(String mText) 
{ 
mTextView.setText(mText); 
} 

Nel vostro risultato attività

//Do not create new object each time you set text. Use the same fragment object which you use for view pager. 
     Your_Fragment mFragment; 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
       switch (requestCode) { 
        case FILE_SELECT_CODE: 
        if (resultCode == RESULT_OK) { 

    //Set text from here 
       mFragment.changeText(imgName); 

       } 
+0

Come il codice di una domanda, ho MyAdapter e inizializzo il mio frammento in questo modo: pubblico Fragment getItem (int position) {Fragment fragmentObject = new firstTab(); ...} ;;;; Come posso accedere a quell'oggetto frammento ? –

+0

Vedere la mia domanda correlata: http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity –

4

È possibile per gonfiare un layout in cui textView è dichiarata:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.your_layout, this, false); 

e poi:

textViewImg = (TextView) view.findViewById(R.id.textViewUrlImgLectura); 
+0

In 'Visualizza view = inflater.inflate (R.layout.your_layout, this, false);' , "questo" deve essere 'ViewGroup' ma nel metodo' onActivityResult' non ne ho. Come posso accedervi? – Lyd

+1

prova ad usare 'null' invece –

+0

Ok, non è' nullo'now ma non cambia il testo. Ho: 'LayoutInflater inflater = (LayoutInflater) getSystemService (Context.LAYOUT_INFLATER_SERVICE); \t Visualizza view = inflater.inflate (R.layout.activity_lectura, null, false); \t textViewImg = (TextView) view.findViewById (R.id.textViewUrlImgLectura); \t System.out.println ("visualizzazione testo:" + textViewImg.getText());/* Ottengo il corretto TextView */ \t textViewImg.setText (imgName); ' – Lyd