简体   繁体   English

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

[英]Can't access outer class from fragment class android

When I try to access outer class with this code: 当我尝试使用此代码访问外部类时:

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

it says: 它说:

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

Here is my Logger.java: 这是我的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;
        }

    }

}

* EDIT * * 编辑 *

Changing this line: 改变这一行:

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

to this: 对此:

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

solved the problem, but that was not what I was looking for. 解决了这个问题,但那不是我想要的。 Thanks to Kapil Vij for correct Answer! 感谢Kapil Vij的正确答案!

change to: 改成:

Logger.this.getApplicationContext()

Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment Logger it-self是您调用getActivity以获取Fragment活动的引用的活动

EDIT 编辑

Saw that you are calling it inside a fragment change you code to: 看到你在一个片段更改中调用它代码:

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

Do this 做这个

ImageView myView = new ImageView(getActivity());

getActivity() method is accessible in fragment class, and ur trying to access it using FragmentActivity class instance. 可以在fragment类中访问getActivity()方法,并尝试使用FragmentActivity类实例访问它。

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

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