2015-10-28 2 views
0

Я разрабатываю приложение для Android, у которого есть вкладка activity.in этого действия есть еще четыре вкладки, которые создаются с помощью Fragments.now я хочу получить данные с вкладки фрагмента в основная вкладка activity.i много искала, но не нашла точного ответа. Если бы это можно было решить. Ниже мой кодполучение данных из вкладок с использованием фрагмента в android

Главная Tab активность

public class TabedActivity extends ActionBarActivity { 

    // Declaring Your View and Variables 
    MobileServiceClient MSC; 
    MobileServiceTable MST; 

    Toolbar toolbar; 
    ViewPager pager; 
    ViewPagerAdapter adapter; 
    SlidingTabLayout tabs; 
    CharSequence Titles[]={"Basic","Education","Profession","Experiance"}; 
    int Numboftabs =4; 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 


     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_tabed); 

     // Creating The Toolbar and setting it as the Toolbar for the activity 

     // toolbar = (Toolbar) findViewById(R.id.tool_bar); 
     //setSupportActionBar(toolbar); 


     // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. 
     adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs); 

     // Assigning ViewPager View and setting the adapter 
     pager = (ViewPager) findViewById(R.id.pager); 
     pager.setAdapter(adapter); 

     // Assiging the Sliding Tab Layout View 
     tabs = (SlidingTabLayout) findViewById(R.id.tabs); 
     tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width 

     // Setting Custom Color for the Scroll bar indicator of the Tab View 
     tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { 
      @Override 
      public int getIndicatorColor(int position) { 
       return getResources().getColor(R.color.tabsScrollColor); 
      } 
     }); 

     // Setting the ViewPager For the SlidingTabsLayout 
     tabs.setViewPager(pager); 
    } 






    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_tabed, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     item.getItemId(); 
     switch (item.getItemId()) { 
      case R.id.action_settings: 
       goToHome(); 
       return true; 
      case R.id.done: 
       Toast.makeText(this, "you select done", Toast.LENGTH_SHORT).show(); 

       return true; 



      default: 
       return super.onOptionsItemSelected(item); 
     } 



     //noinspection SimplifiableIfStatement 

    } 
    public void goToHome(){ 

     Intent gotohome=new Intent(this,MapsActivity.class); 
     startActivity(gotohome); 
    } 
    //the following function was added to update but not working 

public static void settingValues(){ 

и Tab активности

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.EditText; 
import android.widget.Toast; 

/** 
* Created by hp1 on 21-01-2015. 
*/ 
public class Tab1 extends Fragment { 


    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

     View v =inflater.inflate(R.layout.tab_1,container,false); 

     EditText contactNumber= (EditText)v.findViewById(R.id.editTextcontact); 
     EditText address= (EditText)v.findViewById(R.id.editText2); 

     contactNumber.setHint("Your ContactNo Plz"); 
     address.setHint("Your address Plz"); 

     return v; 
    } 
} 

View Page адаптер класса

public class ViewPagerAdapter extends FragmentStatePagerAdapter { 

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created 
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created 


    // Build a Constructor and assign the passed Values to appropriate values in the class 
    public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) { 
     super(fm); 

     this.Titles = mTitles; 
     this.NumbOfTabs = mNumbOfTabsumb; 

    } 

    //This method return the fragment for the every position in the View Pager 
    @Override 
    public Fragment getItem(int position) { 

     if(position == 0) // if the position is 0 we are returning the First tab 
     { 
      Tab1 tab1 = new Tab1(); 
      return tab1; 
     } 
     else if (position==1){ 

      Tab2 tab2 = new Tab2(); 
      return tab2; 
     } 
     else if (position==2){ 
      Tab3 tab3 = new Tab3(); 
      return tab3; 
     } 

     else    // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab 
     { 
      Tab4 tab4=new Tab4(); 
      return tab4; 
     } 


    } 

    // This method return the titles for the Tabs in the Tab Strip 

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

    // This method return the Number of tabs for the tabs Strip 

    @Override 
    public int getCount() { 
     return NumbOfTabs; 
    } 
} 
+0

Вы можете посмотреть здесь http: // stacko verflow.com/questions/32344885/how-to-to-send-data-when-tab-is-selected-or-swipe/32346044#32346044 –

+0

@SatyenUdeshi это тоже отличный ответ, но не решил мою проблему. скажите, пожалуйста, как я могу получить доступ к элементам управления Tab1 в основной деятельности. Например, получите текст EditText и т. д. help –

+0

о том, какой eveent вы хотите получить к этим данным/ –

ответ

1

Редактировать Чтобы получить ссылку на ваше мнение, вы должны заявить, что view(s) на class уровне, например,

public class Tab1 extends Fragment { 

EditTex address,contactNumber; 

@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View v =inflater.inflate(R.layout.tab_1,container,false); 

    contactNumber= (EditText)v.findViewById(R.id.editTextcontact); 
    address= (EditText)v.findViewById(R.id.editText2); 

    contactNumber.setHint("Your ContactNo Plz"); 
    address.setHint("Your address Plz"); 

    return v; 
    } 

    public String getData(){ 
     return address.getText().toString(); 
    } 
} 

Сначала объявить глобальную переменную, чтобы сохранить ссылку на currentPage отображается

int currentPage = 0; // 0 - потому, что изначально отображается страница 0th.

Вы можете получить ссылку на ваш Fragment используя следующий метод:

private static String makeFragmentName(int viewPagerId, int index) { 
    return "android:switcher:" + viewPagerId + ":" + index; 
} 

в вышеприведенном viewPagerId является вашим ViewPager'sid

Вам нужно будет хранить ссылку на current page отображается для этого implement addOnPageChangeListener() на ViewPager и в методе onPageSelected() обновите переменную currentPage.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 
     @Override 
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 

     } 

     @Override 
     public void onPageSelected(int position) { 
      currentPage = position; 
     } 

     @Override 
     public void onPageScrollStateChanged(int state) { 

     } 
    }); 

Теперь для того, чтобы получить данные в onOptionsItemSelected() метода вы можете сделать, как показано ниже

// You will need to check for the index manually and get the reference of the current `Fragment` so a solution to this can be like 

if(currentPage == 0){ 
    Tab1 tab1 = (Tab1)getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.your_view_pager,currentPage)); 
    // always check for null 
    if(tab1 != null){ 
     String data = tab1.getData(); 
    } 
}else if(currentPage == 1){ 
    Tab2 tab2 = (Tab2)getSupportFragmentManager().findFragmentByTag(makeFragmentName(R.id.your_view_pager,currentPage)); 

    if(tab2 != null){ 
     String data = tab2.getData(); 
    } 
} 

... so on 

создать метод в ваших фрагментов для доступа к данным для например

public String getData(){ 
    String data = yourEditText.getText().toString(); 
    return data; 
} 

так же вы можете получить доступ к другие данные, а также, сообщите мне, если вам потребуется более подробная информация

+0

alot спасибо, что это сработало для меня bro.thank you !! –

+0

Рад помочь :) –

+0

Последний вопрос, как вы находите этот пост. public String getData() { Строковые данные = вашEditText.getText(). toString(); данные о возврате; } –

0

это не что иное, как nested fragment основном фрагмента внутри фрагмента (гнездование) - not supported. ame, Nested fragments are not currently supported. Попытка поместить фрагмент в UI другого фрагмента приведет к непредсказуемому и, вероятно, разбитому поведению приложения ..

+0

работает нормально, но проблема в том, что я не могу получить доступ к элементам Tab1 fragment.ie.textview и редактировать текст. Мне нужно только получить доступ к этим элементам из основного TabedActivity. –

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