【问题标题】:getting data from tabs using fragment in android在android中使用片段从选项卡中获取数据
【发布时间】:2015-10-28 09:59:28
【问题描述】:

我正在开发一个具有选项卡活动的 android 应用程序。在此活动中,还有四个选项卡是使用 Fragments 创建的。现在我想从主选项卡活动中的片段选项卡获取数据。我搜索了一个很多但找不到确切的答案。如果有的话可以解决这个问题。下面是我的代码

主选项卡活动

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

查看页面适配器类

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

【问题讨论】:

  • @SatyenUdeshi 这也是一个很好的答案,但没有解决我的问题。你能告诉我如何在主要活动中访问 Tab1 的控件。例如获取 EditText 的文本等等.请帮忙
  • 关于您想要访问该数据的事件/
  • @SatyenUdeshi onOptionsItemSelected 在主选项卡式活动中。
  • 您正在使用FragmentStatePagerAdapter,尝试使用FragmentPagerAdapter,就像我之前给出的答案一样,只需使用正确的index 获得对fragment 的引用,即0,1 ,2,3 得到你想要的数据

标签: java android xml android-fragments tabs


【解决方案1】:

编辑 为了参考您的观点,您应该在class 级别声明view(s),例如

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 - 因为最初显示的是第 0 页。

您可以使用以下方法获得对您的Fragment 的引用:

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

上面的viewPagerId是你的ViewPager'sid

您需要保留在ViewPager 上为此implement addOnPageChangeListener() 显示的current page 的引用,并在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;
}

同样,您也可以访问其他数据,如果您需要更多详细信息,请告诉我

【讨论】:

  • 最后一个问题,您如何找到此声明。 public String getData(){ String data = yourEditText.getText().toString();返回数据; }
  • 这里我无法获得对editText的引用。如果可能,请检查它。thnks
  • 你需要在onCreateView()之外声明EditText
  • 请举例说明
  • 创建空指针异常尝试在空对象引用上调用虚拟方法'android.text.Editable android.widget.EditText.getText()'
【解决方案2】:

这不过是片段(嵌套)中的nested fragment 基本上片段是not supported。你也在做同样的事情,Nested fragments are not currently supported。尝试将一个 Fragment 放入另一个 Fragment 的 UI 中会导致应用程序的未定义和可能损坏的行为..

【讨论】:

  • 它工作正常,但问题是我无法访问 Tab1 fragment.ie.textview 和 Edit Text 的元素..我只想从主 TabedActivity 访问这些元素。
猜你喜欢
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多