简体   繁体   中英

How to set Fragment Textview from the activity it's shown on

I have TestsFragment that extends from Fragment . in the layout of this Fragment there is a TextView (id: textview) There is an Activity called MainActivity : this Activity contain a FrameLayout that shows the Fragment I want to set the textview Text onCreate MainActivity for that I guess I need the view of this Fragment

I have tried this code (OnCreate - MainActivity):

Fragment fragment = new TestsFragment();
View v = getLayoutInflater().inflate(R.layout.fragment_tests, null);
TextView tv = v.findViewById(R.id.textview);
tv.setText("text changed!");

But it doesn't work (No error the text just not chaning)

so can you help me with that? If there any code you need please tell !

MainActivity:

public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
Fragment testsFragment, signsFragment, practiceFragment, accountFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bottomNavigationView = findViewById(R.id.bottom_navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(navListener);


    if(savedInstanceState == null){
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new TestsFragment(), "TestsFragment").commit();
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, new SignsFragment()).commit();
        getSupportFragmentManager().executePendingTransactions();
    }

}

@Override
protected void onStart() {
    super.onStart();
    testsFragment = getSupportFragmentManager().findFragmentByTag("TestsFragment");
    if(testsFragment != null){
        TextView textView = testsFragment.getView().findViewById(R.id.textview);
        textView.setText("Text Changed!");
    }
}



private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;

        switch (item.getItemId()){
            case R.id.nav_signs:
                selectedFragment = new SignsFragment();
                break;

            case R.id.nav_tests:
                selectedFragment = testsFragment;
                break;

            case R.id.nav_practice:
                selectedFragment = new PracticeFragment();
                break;

            case R.id.nav_account:
                selectedFragment = new AccountFragment();
                break;
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
        return true;
    }
};
}

fragments_tests.xml(layout):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#007AFF" android:orientation="vertical">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerview_tests"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:paddingHorizontal="5dp">


</androidx.recyclerview.widget.RecyclerView>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="text not changed"
    android:id="@+id/textview"/>

</LinearLayout>

Solution

  • When users click on each menu item, you always create a new fragment, this is not a good user experience, because when users switch between menu items, they always see a new screen not the screen when they leave before. For example, in SignsFragment , there is an EditText to let users enter their name as "Bob", when they switch to AccountFragment and switch back to SignsFragment , the EditText will be empty (but users expect to see "Bob").

  • To prevent this behavior, we will use addToBackStack() method, so the FragmentManager will keep a reference to all the created fragments. If the fragment does not exist in FragmentManager , it will create a new one, otherwise, it will reuse the existing one.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG_SIGNS_FRAGMENT = "TAG_SIGNS_FRAGMENT";
    private static final String TAG_TESTS_FRAGMENT = "TAG_TESTS_FRAGMENT";
    private static final String TAG_PRACTICE_FRAGMENT = "TAG_PRACTICE_FRAGMENT";
    private static final String TAG_ACCOUNT_FRAGMENT = "TAG_ACCOUNT_FRAGMENT";

    BottomNavigationView bottomNavigationView;

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

        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
        bottomNavigationView.setSelectedItemId(R.id.nav_signs);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            String tag = null;

            // Find the tag of fragment based on menu item position.
            switch (item.getItemId()) {
                case R.id.nav_signs:
                    tag = TAG_SIGNS_FRAGMENT;
                    break;
                case R.id.nav_tests:
                    tag = TAG_TESTS_FRAGMENT;
                    break;
                case R.id.nav_practice:
                    tag = TAG_PRACTICE_FRAGMENT;
                    break;
                case R.id.nav_account:
                    tag = TAG_ACCOUNT_FRAGMENT;
                    break;
            }

            // Find the fragment in FragmentManager.
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);

            // If the fragment is not existed, create a new instance of it, otherwise
            // use the existing one.
            if (fragment == null) {
                switch (tag) {
                    case TAG_SIGNS_FRAGMENT:
                        fragment = new SignsFragment();
                        break;
                    case TAG_TESTS_FRAGMENT:
                        fragment = new TestsFragment("text changed!");
                        break;
                    case TAG_PRACTICE_FRAGMENT:
                        fragment = new PracticeFragment();
                        break;
                    case TAG_ACCOUNT_FRAGMENT:
                        fragment = new AccountFragment();
                        break;
                }
            }
            // Show the fragment on screen.
            showFragment(fragment, tag);
            return true;
        }
    };

    private void showFragment(Fragment fragment, String tag) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment, tag)
                .addToBackStack(tag)
                .commit();
        getSupportFragmentManager().executePendingTransactions();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM