无法在片段中设置文本

时间:2017-08-13 04:36:30

标签: java android android-fragments

我正在尝试从mainActivity调用一个函数来更改我的一个片段中的TextView。我已经阅读了一些关于最佳方式的帖子,但出于某种原因,它们似乎都不适合我。我知道这个功能正在运行,因为一旦按下按钮,吐司就出现了,但由于某种原因,文本不会改变。我想知道问题是什么,或者我是否只是错过了一个额外的步骤。

这是我在mainActivity中调用的方法

 public class MainActivity extends AppCompatActivity implements Tab1Fragment.OnCalcClickListener{
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdpater;
private ViewPager mViewPager;
Tab1Fragment tab1Fragment = new Tab1Fragment();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "onCreate: Starting");

    //initializing FragmentManager so the fragments can communicate
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.container, tab1Fragment);
    fragmentTransaction.commit();

    //declare sections page adapter
    mSectionsPageAdpater = new SectionsPageAdapter(getSupportFragmentManager());

    //Set up the view pager with the sections adapter
    mViewPager = (ViewPager) findViewById(R.id.container);
    setUpViewPager(mViewPager);

    //create a tab layout object and set it's id to tabs (mainActivity.xml)
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    //
}

// create a sections page view adapter
private void setUpViewPager(ViewPager viewPager){
     SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new Tab1Fragment(), "Day");
    adapter.addFragment(new Tab2Fragment(), "Info");
    adapter.addFragment(new Tab3Fragment(), "Week");
    viewPager.setAdapter(adapter);
}

//initialise calculator object
Calculator mainCalculator = new Calculator();


@Override
public void calculateClick(int to_calculate) {
    switch (to_calculate){
        case 1:
            Toast.makeText(getBaseContext(),"working", Toast.LENGTH_SHORT).show();
            mainCalculator.freqDay = mainCalculator.freqDay + 1;
            mainCalculator.freqWeek = mainCalculator.freqWeek + 1;
            mainCalculator.getTotalDay();
            tab1Fragment.updateInfo();
            break;
    }
}

这是我片段的代码

public class Tab1Fragment extends Fragment implements 
View.OnClickListener{
private static final String TAG = "Tab1Fragment";
//Establishing the buttons & Methods
Button btn1;
Button btn2;
TextView dayView;
OnCalcClickListener onCalcClickListener;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1_fragment, container, false);


    //Connecting the buttons to the xml
    btn1 = (Button) view.findViewById(R.id.btn_1);
    btn1.setOnClickListener(this);
    btn2 = (Button) view.findViewById(R.id.btn_2);
    btn2.setOnClickListener(this);
    dayView = (TextView) view.findViewById(R.id.total_Sales_Day);
    return view;
}

//Onclick listener for buttons
public void setOnClickListener(View.OnClickListener listener) {
    btn1.setOnClickListener(listener);
    btn2.setOnClickListener(listener);
}


//method that will bring data back from activity and set the text
public void updateInfo(){
    Toast.makeText(getContext(),"65", Toast.LENGTH_SHORT).show();
    dayView.setText("test");

}

2 个答案:

答案 0 :(得分:0)

要在活动类中调用片段中的方法,您需要这样的内容:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article

        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
}

此处活动是从片段调用updateArticleView方法,而不是updateInfo方法,但您会明白这一点。

还要注意one-pane场景,您需要交换内容并使用Bundle对象推送参数。

有关详细信息,请参阅Deliver a Message to a Fragment

答案 1 :(得分:0)

当你添加片段时,像这样设置一个标签:

MyFragment frag = new MyFragment();
frag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, frag, "TAG").commit();

更新textview时使用findFragmentByTag()

获取片段实例
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("TAG");
fragment.updateInfo();