简体   繁体   中英

Android TextView within viewpager - How to write text to a fragment from MainActivity

Hello everyone and thank you in advance,

I looked all around stackoverflow, but couldn't find the answer to my problem.

I have a viewpager, and two different fragments. I can swipe no problem. I'm getting data from a mp3 stream (artist name and song title). I want to put this data in a TextView every 30secs. My problem is that I don't know, from the Main Activity, how to reach the textview in my fragments. I tried using bundle but ended up getting null on getArguments().

I managed, using interfaces to get my main to do something when I click on a button. This time i want my main to do something, and update text in a fragment.

Here is my code :

MainActivity

package com.radioGMT.radio;


import java.net.URL;    
import android.app.ActionBar;
.
.
.
import com.radioGMT.tabsswipe.adapter.TabsPagerAdapter;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnButtonPlayListener, OnButtonPauseListener {
    private Button button_play;
    private Button button_pause;
    private AudioManager audioManager;
    private TextView textView_info;
    private PhoneStateListener phoneStateListener;
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;    

    public String URL_GMT ="http://goodmorningtoulouse.bcast.infomaniak.ch:8000/radiogmt.mp3";
    boolean finish = false;
    public String data_metadata ="ini";



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

        // Pour Swipe Tabs


        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new TabsPagerAdapter(fragmentManager));

        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);



        // Add 2 tabs, specifying the tab's text and TabListener
        actionBar.addTab(actionBar.newTab().setText("Direct").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText("Programme").setTabListener(this));

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //////
        Here, I want to setText to a fragment

    }



    //Classes fonctions et interfaces


    //Following three allow for extends FragmentActivity implements ActionBar.TabListener
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

TabsPagerAdapter :

package com.radioGMT.tabsswipe.adapter;


import android.support.v4.app.Fragment;
.
.
import com.radioGMT.radio.ProgrammeFragment;

public class TabsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 2;
    }

    @Override
    public Fragment getItem(int index) {
        Fragment fragment = null;

        if (index == 0){
            fragment = new LecteurFragment();
        }

        if (index == 1){
            fragment = new ProgrammeFragment();
        }

        return fragment;
    }   
}

LecteurFragment

package com.radioGMT.radio;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class LecteurFragment extends Fragment implements View.OnClickListener{

    //Declaration des variables
    private TextView textView;
    private Button mButtonPlay;
    private Button mButtonPause;
    private OnButtonPlayListener _mClickListener;
    private OnButtonPauseListener _mClickPause;
    private TextView bottom_text;


    //En cours

    //Interfaces
    public interface OnButtonPlayListener {
        public void onButtonPlayInteraction(View view);
    }

    public interface OnButtonPauseListener {
        public void onButtonPauseInteraction(View view);
    }


    //onCreate
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        mButtonPlay=(Button) view.findViewById(R.id.button_play);
        mButtonPause = (Button) view.findViewById(R.id.button_pause);

        // Le programme surveille le bouton play, au cas ou l'utilisateur appuie dessus 
        mButtonPlay.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        _mClickListener.onButtonPlayInteraction(view);
                    }
                });

        //Le programme surveille le bouton pause, au cas ou l'utilisateur appuie dessus
        mButtonPause.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        _mClickPause.onButtonPauseInteraction(view);
                    }
                });
        return view;
    }


    //onAttach
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            _mClickListener = (OnButtonPlayListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnButtonPlayListener");
        }

        try {
            _mClickPause = (OnButtonPauseListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + "must implement OnButtonPauseListener");
        }

    }

    //onDetach
    @Override
    public void onDetach() {
        super.onDetach();
        _mClickListener = null;
        _mClickPause = null;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }    
}

activity_main.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>

fragment_lecteur.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/Orange"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/RelativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/Orange" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:contentDescription="@string/Header_image"
            android:src="@drawable/logo_header_v2_4" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/Degrade_001"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@layout/gradient_noir_marron"
        android:minHeight="10dp"
        android:orientation="vertical" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/Marron"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button_play"
            style="android:attr/buttonBarButtonStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@android:drawable/ic_media_play"
            android:drawableStart="@android:drawable/ic_media_play"
            android:text="@string/Lecture" />

        <Button
            android:id="@+id/button_pause"
            style="android:attr/buttonBarButtonStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:drawableLeft="@android:drawable/ic_media_pause"
            android:drawableStart="@android:drawable/ic_media_pause"
            android:text="@string/Pause" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/RelativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/Marron" >

        <TextView
            android:id="@+id/textView_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_margin="10dp"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/Degrade_002"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@layout/gradient_marron_noir"
        android:minHeight="10dp"
        android:orientation="vertical" >
    </LinearLayout>

    <Button
        android:id="@+id/bottom_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

To resume, I want to write something in bottom_text in LecteurFragment, from my mainactivity.

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public LecteurFragment lecteur_fragment;
    public ProgrammeFragment programme_fragment;

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
        lecteur_fragment = new LecteurFragment();
        programme_fragment = new ProgrammeFragment();
    }

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

    @Override
    public Fragment getItem(int index) {
        if (index == 0) {
            return lecteur_fragment;
        }
        else if (index == 1){
            return programme_fragment;
        }
        else {
            return null;
        }
    }   
}

And in your activity

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

    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    FragmentManager fragmentManager = getSupportFragmentManager();
    mAdapter = new TabsPagerAdapter(fragmentManager);
    viewPager.setAdapter(mAdapter);

    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    actionBar.addTab(actionBar.newTab().setText("Direct").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("Programme").setTabListener(this));

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
        @Override public void onPageScrolled(int arg0, float arg1, int arg2) { }
        @Override public void onPageScrollStateChanged(int arg0) { }
    });

    MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    //call a function `updateTextView` in the fragment with the value, and the fragment will update its textview..
    ((LecteurFragment)mAdapter.getItem(0)).updateTextView("myValue");

}

Now in your LecteurFragment

public class LecteurFragment extends Fragment implements View.OnClickListener {

    ...
    public void updateTextView(String value_to_set) {
        ((TextView) getView().findViewById(R.id.id_of_textview)).setText(value_to_set);
    }
    ...
}

Probably the official approach would be creating an Interface with a method that returns an String .

This interface would be must implemented in the MainActiviy and past as parameter on the TabsPagerAdapter constructor. After that, it could be assigned to the LecteurFragment and use it.

But it isn't really the approach that i would take it. I would just create an static String on MainActivity:

//MainActivity

public static String artistName;

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

    //before call setAdapter
    artistName = getArtistName()

    FragmentManager fragmentManager = getSupportFragmentManager();
    viewPager.setAdapter(new TabsPagerAdapter(fragmentManager));

    //etc

}

And use it in the LectureFragment

@Override   
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_lecteur, container, false);
    TextView tv_artist_name = (TextView) view.findViewById(R.id.tv_artist_name);
    tv_artist_name.setText(MainActivity.artistName);
}

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