【问题标题】:Get edittext value from fragment in viewpager从viewpager中的片段获取edittext值
【发布时间】:2014-07-17 06:50:35
【问题描述】:

我有一个这样的视图寻呼机,

public class MainActivity extends ActionBarActivity implements TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
 * derivative, which will keep every loaded fragment in memory. If this
 * becomes too memory intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayUseLogoEnabled(false);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setDisplayShowHomeEnabled(false);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(2);

    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
        // below).
        if (position == 0)
            return Fragment1.newInstance();
        else
            return Fragment2.newInstance();
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        }
        return null;
    }
}

@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
    // TODO Auto-generated method stub

}

}

Fragment1

public class Fragment1 extends Fragment {

private EditText et1;

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static Fragment1 newInstance() {
    Fragment1 fragment = new Fragment1();
    return fragment;
}

public Fragment1() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container,
            false);
    return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    et1 = (EditText) getView().findViewById(R.id.text1);
}

}

Fragmet2

public class Fragment2 extends Fragment {

private Button btnGetValues;
/**
 * Returns a new instance of this fragment for the given section number.
 */
public static Fragment2 newInstance() {
    Fragment2 fragment = new Fragment2();
    return fragment;
}

public Fragment2() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment2, container,
            false);
    return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    btnGetValues = (Button) getView().findViewById(R.id.button1);
    btnGetValues.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Here I want to get the value of edittext which is in fragment1.
        }
    });
}

}

如您所见,我想在Button 点击事件中获取EdiText 中的Fragment 的值,按钮在Fragment2 中。我用谷歌搜索了很多,但我找不到任何答案,任何帮助都将是非常可观的。

【问题讨论】:

  • 尝试在 Activity 中取一个变量并将 EditText 值分配给该变量,并在 EditText 更改时更改它的值现在尝试在按钮单击时使用此变量。
  • @Gunaseelan 试试我的解决方案

标签: java android android-fragments


【解决方案1】:

在Activity中创建String变量。

String text;

在活动中放置以下功能:

void onTextChanged(String text){
   this.text=text;
   //Receive new text here
}


void onButtonClick(){
   //use current value of text variable as the latest edit text value in fragment1
}

并且在fragment1中点击按钮:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    et1 = (EditText) getView().findViewById(R.id.text1);

et1.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
       ((MainActivity)getActivity()).onTextChanged(s);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
   }   

在片段 2 中:

btnGetValues.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        // Here I want to get the value of edittext which is in fragment1.
    ((MainActivity)getActivity()).onButtonClick();

 }
});

在fragment改变(Swipe)的情况下,当fragment1消失而fragment2可见时,你可以简单地收集一个域对象中的所有值,并调用传递这个对象的活动函数。

【讨论】:

  • @Gunaseelan 你也可以创建一个具有这两种方法的接口,而不是类型转换活动,并使活动实现这个接口。最后将活动引用传递给片段。
  • 我会试试这个,然后回到你身边的朋友。
  • @vipulmittal 我认为你需要使用rootView.findViewById(R.id.text1); 而不是getView().findViewById(R.id.text1);
  • 我不确定这会有什么不同。但是可以将相同的代码移至 onCreateView 并且可以使用 rootView 代替 getView()。但是,我认为这也应该有效。
  • @vipulmittal 如果你测试并且你说这项工作我接受,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多