来自活动的Android Fragment TextView setText

时间:2017-05-17 18:01:17

标签: android android-studio android-fragments

我遇到了问题:我有两个标签的TabLayout。一个选项卡包含TextView。 我想从MainActivity更改TextView的文本(稍后从MainActivity中的Thread更改)。但它引发了NPE,我不知道如何解决它。

这是我的MainActivity.java代码:

public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

public static ThreadConnected myThreadConnected;
TabTerminal tabT;

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

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    tabT = new TabTerminal();
    tabT.setText("324");
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        //Returning the current tabs
        switch (position) {
            case 0:
                TabControl tab1 = new TabControl();
                return tab1;
            case 1:
                TabTerminal tab2 = new TabTerminal();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // ...
    }
}

}

这是FragView with TextView:

public class TabTerminal extends Fragment {

static TextView txtterminalout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_terminal, container, false);
    TextView txtterminalout = (TextView) rootView.findViewById(R.id.terminalout);

    return rootView;
}

public void setText(String text) {
    TextView t = (TextView) getView().findViewById(R.id.terminalout);
    t.setText(text);
}

}

2 个答案:

答案 0 :(得分:1)

您可以在setText() fragment中使用MainActivity方式拨打FragmentManager fm = getSupportFragmentManager(); //if you added fragment via layout xml YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id); fragment.setText(); 方法,如下所示:

tag

如果您在添加fragment后通过代码添加了片段并使用了findFragmentByTag字符串,请使用YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag"); 代替:

strtok(char *str, const char *delim)

希望它有所帮助。

答案 1 :(得分:0)

onCreate()结束时,您正在创建新的片段并尝试setText()。因为它没有膨胀你得到NPO。

你想要的是抓住已经膨胀的片段并在其上setText()。 试试getSupportFragmentManager().findFragmentById(R.id.your_fragment).setText()