tActivity在ViewPager获取TextView中的I

tActivity在ViewPager获取TextView中的I

本文介绍了从FragmentActivity在ViewPager获取TextView中的ID在片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与 ViewPager 3 片段,我想改变的TextView 第三页。

在该网页我有一个按钮,当其pressed,去标清画面选择之一。完成后,返回到页面,并要更新的TextView 与图像的路径。问题是,当我尝试访问的TextView FragmentActivity 为null。

这是我的code

SherlockFragmentActivity:

 公共类TabsFacturasActivity扩展SherlockFragmentActivity {

    保护所有MyApplication所有MyApplication;
    私有静态最终诠释FILE_SELECT_ code = 0;

    私人MyAdapter mAdapter;
    私人ViewPager mPager;
    私人PageIndicator mIndicator;
    私人TextView的textViewImg;

    私人诠释lecturas = 0;
    私人SimpleDateFormat的日期格式=新的SimpleDateFormat(DD / MM / YYYY);
    私人布尔adjunto = FALSE;
    私人字符串文件路径;
    私人布尔esLecturaAT = FALSE;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.fragment_pager);

        //获取应用程序实例
        所有MyApplication =(所有MyApplication)getApplication();

        //需要获得该视图
        textViewImg =(TextView中)findViewById(R.id.textViewUrlImgLectura);

        // Creamos拉LISTA
        链表<字符串> direcciones =新的LinkedList<字符串>();
        ArrayList的< TuplaCupsWS> 。迪尔斯= myApplication.getUsuarioActual()getCups();
        为(中间体DIR = 0;目录&所述; myApplication.getUsuarioActual()getCups()的大小(); DIR ++){
            direcciones.add(新的字符串(dirs.get(DIR).getDireccion()));
        }

        INT标签= getIntent()getIntExtra(标签,0);

        mAdapter =新MyAdapter(getSupportFragmentManager());

        mPager =(ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mPager.setCurrentItem(标签);

        mIndicator =(TitlePageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);

        getSupportActionBar()setDisplayShowTitleEnabled(假)。
        getSupportActionBar()的setIcon(R.drawable.logo_factorenergia_peque)。

        / **创建一个数组适配器来填充的DropDownList * /
        ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串>(
                getBaseContext(),android.R.layout.simple_spinner_dropdown_item,direcciones);

        / **启用下拉列表导航操​​作栏* /
        。getSupportActionBar()setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        / **定义导航监听* /
        OnNavigationListener navigationListener =新OnNavigationListener(){

            @覆盖
            公共布尔onNavigationItemSelected(INT itemPosition,长的itemId){
                返回false;
            }
        };

        / **设置下拉列表项和项目导航侦听器的动作条* /
        getSupportActionBar()。setListNavigationCallbacks(适配器,
                (com.actionbarsherlock.app.ActionBar.OnNavigationListener)
                navigationListener);
    }

    @覆盖
    保护无效onActivityResult(INT申请code,INT结果code,意图数据){
        开关(要求code){
            案例FILE_SELECT_ code:
            如果(结果code == RESULT_OK){
                adjunto = TRUE;
                //获取所选文件的URI
                开放的我们的uri = data.getData();
                //获取路径
                字符串路径=;
                尝试 {
                    PATH = MyUtility.getPath(这一点,URI);
                }赶上(的URISyntaxException E){
                    myApplication.throwException(本);
                    e.printStackTrace();
                }
                字符串imgName = path.split(/)[path.split(/),长度为1];
                textViewImg.setText(imgName); //这里textViewImg为空
                文件路径=路径;
            }
            打破;
        }
        super.onActivityResult(要求code,因此code,数据);
    }

    //方法执行时按钮是pressed
    公共无效examinar(查看视图){
        mostrarFileChooser();
    }

    私人无效mostrarFileChooser(){
        意向意图=新的意图(Intent.ACTION_PICK);
        intent.setType(图像/ *);

        尝试 {
            startActivityForResult(意向,FILE_SELECT_ code);
        }赶上(android.content.ActivityNotFoundException前){
        }
    }

    私有静态类MyAdapter扩展FragmentPagerAdapter {

        私有String []标题= {VER FACTURAS,VER CONSUMO,INTRODUCIR LECTURA};

        公共MyAdapter(FragmentManager fragmentManager){
            超(fragmentManager);
        }

        @覆盖
        公共CharSequence的getPageTitle(INT位置){
            回到标题[位置]
        }

        @覆盖
        公共片段的getItem(INT位置){
            开关(位置){
            情况下0://片段#0
                返回新FacturasActivity();
            案例1://片段#1
                返回新ConsumoActivity();
            案例2://片段#2
                返回新LecturaActivity();
            }
            //返回新MyFragment();
            返回null;
        }

        @覆盖
        公众诠释getCount将(){
            返回titles.length;
        }
    }

}
 

fragment_pager.xml

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=垂直
    工具:上下文=TabsFacturasActivity。>

    < com.viewpagerindicator.TitlePageIndicator
        机器人:ID =@ + ID /指示器
        机器人:填充=10dip
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_width =FILL_PARENT/>

    < android.support.v4.view.ViewPager
        机器人:ID =@ + ID /寻呼机
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =0dp
        机器人:layout_weight =1
        机器人:后台=#1184A4E8/>

< / LinearLayout中>
 

解决方案

您从片段活动着访问文本视图,因为它位于片段和您的片段活动布局没有任何文本视图 ID 。你必须从你的访问文本视图中的第三片段,你在它的布局中使用它。然后访问对象片段的活性

您的片段做这样的事情

  TextView的mTextView;
mTextView =(TextView中)getView()findViewById(R.id.your_text_view)。
 

创建这样的功能

 公共无效changeText(字符串MTEXT)
{
mTextView.setText(MTEXT);
}
 

在活动成果

  //不要创建新的对象,每次设置文本的时间。使用您使用视图寻呼机相同的片段对象。
        Your_Fragment mFragment;
         保护无效onActivityResult(INT申请code,INT结果code,意图数据){
                开关(要求code){
                    案例FILE_SELECT_ code:
                    如果(结果code == RESULT_OK){

    //从这里设置文本
                mFragment.changeText(imgName);

               }
 

I'm working with ViewPager with 3 Fragments and I want to change text of TextView in third page.

In that page I have a Buttonthat when its pressed, go to SD images to select one. When done, returns to page and want to update TextView with path of that image. The problem is that when I try to access that TextViewfrom FragmentActivityit is null.

Here is my code

SherlockFragmentActivity:

public class TabsFacturasActivity extends SherlockFragmentActivity {

    protected MyApplication myApplication;
    private static final int FILE_SELECT_CODE = 0;

    private MyAdapter mAdapter;
    private ViewPager mPager;
    private PageIndicator mIndicator;
    private TextView textViewImg;

    private int lecturas = 0;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    private boolean adjunto = false;
    private String filePath;
    private boolean esLecturaAT = false;

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

        // Get the application instance
        myApplication = (MyApplication)getApplication();

        //Need to get that view
        textViewImg = (TextView) findViewById(R.id.textViewUrlImgLectura);

        //Creamos la lista
        LinkedList<String> direcciones = new LinkedList<String>();
        ArrayList<TuplaCupsWS> dirs = myApplication.getUsuarioActual().getCups();
        for(int dir = 0; dir < myApplication.getUsuarioActual().getCups().size(); dir++) {
            direcciones.add(new String(dirs.get(dir).getDireccion()));
        }

        int tab = getIntent().getIntExtra("tab", 0);

        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager)findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mPager.setCurrentItem(tab);

        mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setIcon(R.drawable.logo_factorenergia_peque);

        /** Create an array adapter to populate dropdownlist */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getBaseContext(), android.R.layout.simple_spinner_dropdown_item, direcciones);

        /** Enabling dropdown list navigation for the action bar */
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        /** Defining Navigation listener */
        OnNavigationListener navigationListener = new OnNavigationListener() {

            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {
                return false;
            }
        };

        /** Setting dropdown items and item navigation listener for the actionbar */
        getSupportActionBar().setListNavigationCallbacks(adapter,
                (com.actionbarsherlock.app.ActionBar.OnNavigationListener)
                navigationListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {
                adjunto = true;
                // Get the Uri of the selected file
                Uri uri = data.getData();
                // Get the path
                String path = "";
                try {
                    path = MyUtility.getPath(this, uri);
                } catch (URISyntaxException e) {
                    myApplication.throwException(this);
                    e.printStackTrace();
                }
                String imgName = path.split("/")[path.split("/").length-1];
                textViewImg.setText(imgName); //Here textViewImg is null
                filePath = path;
            }
            break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //Method executed when Button is pressed
    public void examinar(View view) {
        mostrarFileChooser();
    }

    private void mostrarFileChooser() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");

        try {
            startActivityForResult(intent, FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
        }
    }

    private static class MyAdapter extends FragmentPagerAdapter {

        private String[] titles = { "VER FACTURAS", "VER CONSUMO", "INTRODUCIR LECTURA" };

        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0: // Fragment # 0
                return new FacturasActivity();
            case 1: // Fragment # 1
                return new ConsumoActivity();
            case 2:// Fragment # 2
                return new LecturaActivity();
            }
            //return new MyFragment();
            return null;
        }

        @Override
        public int getCount() {
            return titles.length;
        }
    }

}

fragment_pager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".TabsFacturasActivity" >

    <com.viewpagerindicator.TitlePageIndicator
        android:id="@+id/indicator"
        android:padding="10dip"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#1184A4E8" />

</LinearLayout>
解决方案

You cant access text view from fragment activity because its located on fragment and your fragment activity layout don't have any text view with this id. You have to access text view from your third fragment where you used it in its layout. Then access that object from your fragment activity.

in your fragment do something like this

TextView mTextView;
mTextView = (TextView)getView().findViewById(R.id.your_text_view);

Create a function like this

public void changeText(String mText)
{
mTextView.setText(mText);
}

In your activity result

//Do not create new object each time you set text. Use the same fragment object which you use for view pager.
        Your_Fragment mFragment;
         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                switch (requestCode) {
                    case FILE_SELECT_CODE:
                    if (resultCode == RESULT_OK) {

    //Set text from here
                mFragment.changeText(imgName);

               }

这篇关于从FragmentActivity在ViewPager获取TextView中的ID在片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:19