从具有函数的活动访问片段的视图

时间:2015-09-28 13:28:05

标签: java android android-fragments

我正在尝试从de活动中的片段textview动态更改文本,但我不断获得'无法获取root'错误。我试图在onCreateView和onActivityCreated里面实例化textview,但它不起作用。如何更改活动内部的片段文本视图中的文本?

片段xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>

片段代码:

public class TabFragment1 extends Fragment {
    private TextView tv;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
        return view;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        tv = (TextView) getView().findViewById(R.id.textView);
   }
    public void setText(String text){
        tv.setText(text);
    }

}

Main xml:

<RelativeLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"/>
</RelativeLayout>

主要代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        TabFragment1 t1 = new TabFragment1();
        TabFragment2 t2 = new TabFragment2();
        TabFragment3 t3 = new TabFragment3();
        adapter.newFrag(t1);
        adapter.newFrag(t2);
        adapter.newFrag(t3);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        t1.setText("HELLO WORLD");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

PagerAdapter:

public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    List<Fragment> aFrag;
    public PagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        aFrag = new ArrayList<Fragment>();
    }
    public void newFrag(Fragment f){
        aFrag.add(f);
    }
    @Override
    public Fragment getItem(int position) {

        return aFrag.get(position);
    }

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

1 个答案:

答案 0 :(得分:3)

您尝试在视图上设置文字,但此视图未创建,此片段尚未创建。如果您想从活动中设置文本,可以将 bundle 传递给带有该文本的片段参数,并在片段chceck包中设置文本。稍后如果您想要更改此片段中的文本,则可以使用您的函数。

public class TabFragment1 extends Fragment {
private TextView tv;

public static TabFragment1 create(String text){
   Bundle b = new Bundle();
   b.putString("textdata",text);
   TabFragment1  f = new TabFragment1();
   f.setArguments(b);
   return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
    tv = (TextView) view.findViewById(R.id.textView);
    if(getArguments()!=null){
      tv.setText(getArguments().getString("textdata"));
    }

    return view;
}

    public void setText(String text){
    tv.setText(text);
}

}

在您的活动中使用静态方法创建此片段:

 TabFragment1 t1 =TabFragment1.create("HELLO WORLD");

您的基础代码的硬核执行是:

new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);