繁体   English   中英

viewpager中的Android TextView-如何将文本写入MainActivity中的片段

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

大家好,谢谢!

我到处都是stackoverflow,但是找不到我的问题的答案。

我有一个viewpager和两个不同的片段。 我可以顺利刷卡。 我正在从mp3流(歌手姓名和歌曲名称)中获取数据。 我想每30秒将此数据放入TextView中。 我的问题是,从主要活动中,我不知道如何到达片段中的textview。 我尝试使用捆绑软件,但最终在getArguments()上获取了null。

我设法通过使用界面来使我的主体在单击按钮时执行某些操作。 这次,我希望我的主要人员做一些事情,并更新片段中的文本。

这是我的代码:

主要活动

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>

要恢复,我想从我的mainactivity中的bottom_text中写一些东西。

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;
        }
    }   
}

在你的活动中

@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");

}

现在在您的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);
    }
    ...
}

官方的方法可能是使用返回String的方法创建一个Interface

此接口必须在MainActiviy中实现,并且必须作为TabsPagerAdapter构造函数上的参数来实现。 之后,可以将其分配给LecteurFragment并使用它。

但这并不是我真正采用的方法。 我只是在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

}

并在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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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