无法从片段类android访问外部类

时间:2014-02-01 15:00:01

标签: java android eclipse android-fragments

当我尝试使用以下代码访问外部类时:

ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());

它说:

The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope

这是我的Logger.java:

import java.util.Locale;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;


public class Logger extends FragmentActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    static boolean isBoxOpen = false;

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

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setTitle("Sosyaaal");
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));


        Thread connectivity = new Thread(){
            public void run(){

                try {
                    while(true)
                    {
                        while(!isBoxOpen)
                        {

                            if( !isOnline() )
                            {
                                isBoxOpen = true;
                                  // display error
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                          new AlertDialog.Builder(Logger.this)
                                          .setTitle("Bağlantı Sorunu")
                                          .setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
                                          .setCancelable(false)
                                          .setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener() 
                                           {               
                                             public void onClick(DialogInterface dialog, int which) 
                                             { 
                                                  Logger.isBoxOpen = false;// Try Again
                                             }
                                           })
                                           .show();
                                     }
                                });
                            }

                        }
                    }
                   } catch (Exception e) {

                   }
            }


        };

        connectivity.start();


        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.logger, menu);
        return true;
    }

    public boolean isOnline() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                // Giriş fragment activity
                return new GirisFragment();
            case 1:
                // Kayıt fragment activity
                return new KayitFragment();
            }

            return null;
        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class GirisFragment extends Fragment {

        public static final String ARG_SECTION_NUMBER = "section_number";

        public GirisFragment() {
        }

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

            return rootView;
        }
    }


    public static class KayitFragment extends Fragment {

        public static final String ARG_SECTION_NUMBER = "section_number";
        private ImageSwitcher cinsiyetSwitcher; 

        public KayitFragment() {
        }

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

            cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
            cinsiyetSwitcher.setFactory(new ViewFactory() {

                   @Override
                   public View makeView() {
                      ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
                      myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                      return myView;
                       }

                   });

            return rootView;
        }

    }

}

*的 修改 *

更改此行:

ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());

到此:

ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());

解决了这个问题,但那不是我想要的。感谢Kapil Vij的正确答案!

2 个答案:

答案 0 :(得分:1)

更改为:

Logger.this.getApplicationContext()

记录器it-self是您致电getActivity的活动,以获取Fragment

内活动的参考

修改

看到你在代码改为的片段更改中调用它:

 ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());

答案 1 :(得分:1)

这样做

ImageView myView = new ImageView(getActivity());
可以在fragment类中访问

getActivity()方法,并尝试使用FragmentActivity类实例访问它。