Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

android - how to control/modify the activity textview from viewpager fragment

enter image description here I have a viewpager which has five tab and control the tab with tablayout. the problem that i have is that the title doesn't change when want to go from one activity to another activity. the thing that i do is that i changed the textview title in tablayout in onTabSelected in the activity but in both on select tab and in on reselect tab method but sometimes it doesn't change anymore. another thing that makes the point is the map which i use the address of the map in my main activity title. i changed the address using setOnCameraChangeListener method and the problem with this case is that it run several time even when i am in another fragment and because i used it's address in my main activity title it change it.

at he also changed the title in both onViewCreate and onCreateView in each fragment but it doesn't work fine.

this is what everything that i did:

public class MainPageActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    public Context context;
    public Typeface tf;
    public LinearLayout linearLayout;
    public static boolean a=false;
    private CustomViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.home,
            R.drawable.ic_tab_montakhab,
            R.drawable.ic_tab_search,
            R.drawable.ic_tab_issue,
            R.drawable.ic_tab_profile
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
         tf = Typeface.createFromAsset(getAssets(), "IRANSans_Bold.ttf");
        context=this;

        TextView google_header_address=(TextView)findViewById(R.id.google_header_address);

        tabCustomization();

        setupTabIcons();

        tabLayout.getTabAt(0).getIcon().setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
        linearLayout=(LinearLayout)tabLayout.getTabAt(0).getCustomView();
        ImageView firstTab=(ImageView)linearLayout.getChildAt(0);
        firstTab.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);


        google_header_address.setText("");


        google_header_address.setVisibility(View.VISIBLE);


    }


    private void tabCustomization() {
        viewPager = (CustomViewPager) findViewById(R.id.viewPager);
        viewPager.setPagingEnabled(false);

        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(viewPager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new MenuFragment(), "tab1");

        adapter.addFragment(new AddressFragment(), "tab2");
        adapter.addFragment(new SearchFragment(), "tab3");
        adapter.addFragment(new IssueFragment(), "tab4");
        adapter.addFragment(new ProfileFragment(), "tab5");

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(5);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);


            tab.setCustomView(adapter.getTabView(tabLayout,i));

        }


        ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        Log.i("TabChild",String.valueOf(tabsCount));


// Iterate over all tabs and set the custom view

    }

    public void setupViewPager(ViewPager viewPager) {

    }
    private void setupTabIcons() {

        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){


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

                TabChanges(tab);

            }

            private void TabChanges(TabLayout.Tab tab) {
                linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);


                switch (tab.getPosition())
                {
                    case 0:
                        Log.d("Position", String.valueOf(tab.getPosition()));


                        google_header_address.setVisibility(View.VISIBLE);
                        google_header_address.setText("");

                        ClearFragmentStack();
                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.text_size_bw_small)),Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Log.d("Position", String.valueOf(tab.getPosition()));
                    google_header_address.setText("tab2 title");

                        ClearFragmentStack();



                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;
                    case 2:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab3 title ");

                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)),Toast.LENGTH_LONG).show();
                        break;
                    case 3:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab4 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));

                        break;
                    case 4:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab5 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;

                }
            }

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

                 linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);
                google_header_address.setText("");
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);

                switch (tab.getPosition())
                {

                    case 0:
                        Log.d("Position", String.valueOf(tab.getPosition()));

                        google_header_address.setVisibility(View.VISIBLE);
                        google_header_address.setText("");

                        ClearFragmentStack();
                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.text_size_bw_small)),Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab2 title");

                        ClearFragmentStack();



                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;
                    case 2:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab3 title");

                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)),Toast.LENGTH_LONG).show();
                        break;
                    case 3:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab4 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));

                        break;
                    case 4:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab5 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;

                }
            }
        });


    }

    private void ClearFragmentStack() {
        FragmentManager fm = getSupportFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }


        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        public View getCustomView(TabLayout tabLayout,int position){
            View view = LayoutInflater.from(getApplicationContext())
                    .inflate(R.layout.custom_tab, tabLayout, false);
            TextView textView= (TextView) view.findViewById(R.id.tabText);

            textView.setText(getPageTitle(position));
            textView.setTypeface(tf);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView.setImageResource(tabIcons[position]);

            return view;
        }
        public View getTabView(TabLayout tabLayout,int position) {
            // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView

            View view = LayoutInflater.from(getApplicationContext())
                    .inflate(R.layout.custom_tab, tabLayout, false);
            TextView textView= (TextView) view.findViewById(R.id.tabText);

            textView.setText(getPageTitle(position));
            textView.setTypeface(tf);

            ImageView imageView = (ImageView) view.findViewById

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An easier approach would be to use an EventBus . Which allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration. In order to use EventBus in Android, inside your gradle(app level) add:

compile 'org.greenrobot:eventbus:3.0.0'

Now you'll need to create an Event . An event is just an object that is posted from the sender on the bus and will be delivered to any receiver class subscribing to the same event type. That's it!. So for this purpose we'll create a sample Event class:

    public class HelloWorldEvent {
    private final String message;

    public HelloWorldEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

Now the next step is to create a Sender . Which allows you to post any event from any part of your whole Android application. So in your case you can send from Fragments, viewpager,etc . This is how you do it:

EventBus.getDefault().post(new HelloWorldEvent("Hello EventBus!”);

So this sends a new event, however in order to receive this, you'll need someone to receive it. So in order to listen from any activity, say from your activity class, at first you'll need to register it:

EventBus.getDefault().register(this);

Then inside that class define a new method :

// This method will be called when a HelloWorldEvent is posted
@Subscribe
public void onEvent(HelloWorldEvent event){
  // your implementation
  Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}

So, what happens is whenever an Event is sent, it will be received by the receiver . So You can create one Event and add multiple listeners to it. And it will work fine, as shown in the below image:

enter image description here

More info on the EventBus library is available here:

A simpler tutorial on EventBus is available here:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...