问题描述
这使我发疯.基本上,我想创建一个 ViewPager
并向其中添加一些 Fragment
.然后,我要做的就是在 Fragment
的 TextView
之一中设置一个值.我可以很好地添加 Fragment
,然后将它们附加,但是当我进入 findViewById()
中的第一个 TextView
时, Fragment
会引发 NullPointerException
.我对我一生一无所知.
This one is driving me nuts. Basically, I want to create a ViewPager
and add a few Fragment
s to it. Then, all I want to do, it set a value in one of the Fragment
's TextView
s. I can add the Fragment
s fine, and they attach, but when I go to findViewById()
for one of the TextView
s in the first Fragment
it throws a NullPointerException
. I, for the life of me, can't figure out why.
到目前为止,这是我的代码,请告诉我是否需要更多.
Here's my code so far, let me know if more is needed please.
public class SheetActivity extends FragmentActivity {
// /////////////////////////////////////////////////////////////////////////
// Variable Declaration
// /////////////////////////////////////////////////////////////////////////
private ViewPager viewPager;
private PagerTitleStrip titleStrip;
private String type;
private FragmentPagerAdapter fragmentPager; //UPDATE
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheet);
viewPager = (ViewPager) findViewById(R.id.viewPager);
titleStrip = (PagerTitleStrip) findViewById(R.id.viewPagerTitleStrip);
// Determine which type of sheet to create
Intent intent = getIntent();
this.type = intent.getStringExtra("type");
FragmentManager manager = getSupportFragmentManager();
switch (type) {
case "1":
viewPager.setAdapter(new InstallAdapter(manager));
break;
case "2":
viewPager.setAdapter(new InstallAdapter(manager));
break;
}
fragmentPager = (FragmentPagerAdapter) viewPager.getAdapter(); //UPDATE
}
@Override
public void onResume() {
super.onResume();
fragmentPager.getItem(0).setText("something"); //UPDATE
}
class MyAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Title1", "Title2" };
private final int PAGE_COUNT = TITLES.length;
private ArrayList<Fragment> FRAGMENTS = null;
public MyAdapter(FragmentManager fm) {
super(fm);
FRAGMENTS = new ArrayList<Fragment>();
FRAGMENTS.add(new FragmentA());
FRAGMENTS.add(new FragmentB());
}
@Override
public Fragment getItem(int pos) {
return FRAGMENTS.get(pos);
}
@Override
public int getCount() {
return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int pos) {
return TITLES[pos];
}
}
}
我创建的所有 Fragment
都仅覆盖了 onCreateView()
方法,因此我可以显示正确的XML布局.除此之外,它们是股票".为什么我不能与任何 Fragment
s中的元素进行交互?
All of Fragment
s I created only have the onCreateView()
method overridden so I can display the proper XML layout. Other than that they are 'stock'. Why can't I interact with elements in any of the Fragment
s?
更新:
这样的事吗?
public class FragmentA extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle inState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
public void setText(String text) {
TextView t = (TextView) getView().findViewById(R.id.someTextView); //UPDATE
t.setText(text);
}
}
片段A的XML布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/someTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="22sp" />
</LinearLayout>
推荐答案
除非计划在运行时更改值,否则可以将值作为参数传递给片段.使用Bundle将其作为args传递到Fragment,然后从args检索它来完成此操作.此处更多信息.如果执行此操作,则新片段的实例化可能类似于以下内容:
Unless you are planning to change the value at runtime, you can pass the value into the fragment as a parameter. It is done my using a Bundle and passing it as args into a Fragment, which then retrieves it from it's args. More info here. If you implement this, your instantiation of new Fragments might look something like this:
public InstallAdapter(FragmentManager fm) {
super(fm);
FRAGMENTS = new ArrayList<Fragment>();
FRAGMENTS.add(FragmentA.newInstance("<text to set to the TextView>"));
FRAGMENTS.add(FragmentB.newInstance("<text to set to the TextView>"));
}
但是,如果您打算在运行时更新该值(它将随着用户运行该应用程序而改变),那么您想使用一个接口来引导您的片段和活动之间的通信.此处的信息.这可能是这样的:
If, however, you are planning to update the value at runtime (it will change as user is running the app), then you want to use an Interface to channell communication between your fragment and your activity. Info here. This is what it might look like:
//Declare your values for activity;
ISetTextInFragment setText;
ISetTextInFragment setText2;
...
//Add interface
public interface ISetTextInFragment{
public abstract void showText(String testToShow);
}
...
//your new InstallAdapter
public InstallAdapter(FragmentManager fm) {
super(fm);
FRAGMENTS = new ArrayList<Fragment>();
Fragment fragA = new FragmentA();
setText= (ISetTextInFragment)fragA;
FRAGMENTS.add(fragA);
Fragment fragB = new FragmentB();
setText2= (ISetTextInFragment)fragB;
FRAGMENTS.add(fragB);
}
//then, you can do this from your activity:
...
setText.showText("text to show");
...
,它将更新片段中的文本视图.
and it will update your text view in the fragment.
虽然可以更轻松"地完成这些操作,但还是建议使用这些方法,因为它们可以减少发生错误的机会,并使代码更具可读性和可维护性.
While it can be done "more easily", these methods are recomended because they reduce chances of bugs and make code a lot more readable and maintainable.
这是您的Fragment的外观(修改您的代码):
this is what your Fragment should look like (modified your code):
public class FragmentA extends Fragment implements ISetTextInFragment {
TextView myTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle inState) {
View v = inflater.inflate(R.layout.fragment_a, container, false);
myTextView = (TextView)v.findViewbyId(R.id.someTextView)
return v;
}
@Override
public void showText(String text) {
myTextView.setText(text);
}
}
如果在那之后您仍然遇到空指针异常,则您的TextView不在我需要的位置,即在R.layout.fragment_a文件中,并且需要将其放置在该位置.当然,除非您在片段完成加载之前调用接口方法.
If after that you are still getting a null pointer exception, your TextView is NOT located where it needs to me, namely in the R.layout.fragment_a filem, and it needs to be located there. Unless you are calling the interface method BEFORE the fragment finished loading, of course.
这篇关于Android在FragmentPagerAdapter中的Fragment中设置TextView的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!