Android - 在一个Pager中获取Fragment的上下文

5

我有一个使用pager作为导航的Android应用程序。对于选项卡,我有3个布局作为内容。其中一个片段是一个画廊,我想向其中添加图像。为此,我需要设置一个ImageAdapter,但我需要知道如何访问片段的上下文。

final LayoutInflater factory = getLayoutInflater();
final View view = factory.inflate(R.layout.pictures, null);
Gallery g = (Gallery) view.findViewById(R.id.gallery1);
g.setAdapter(new ImageAdapter(view.getContext()));

我在onCreate方法中使用上述代码获取不是contentview的布局中的画廊。我必须为ImageAdapter提供一个Context。但是那里我需要设置什么上下文?

编辑:这是我的完整代码:

package com.bw2801.uwelugemediathek;

import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.database.DataSetObserver;
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.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
PicturesSectionFragment ps = new PicturesSectionFragment();

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

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

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

    final LayoutInflater factory = getLayoutInflater();
    final View view = factory.inflate(R.layout.pictures, null);
    Gallery g = (Gallery) view.findViewById(R.id.gallery1);
    g.setAdapter(new ImageAdapter(ps.getActivity()));
}

public class ImageAdapter extends BaseAdapter { 
    private Context mContext;

    private Integer[] mImageIds = {
            R.drawable.image01,
            R.drawable.image02,
            R.drawable.image03,
            R.drawable.image04,
            R.drawable.image05,
            R.drawable.image06,
            R.drawable.image07,
            R.drawable.image08,
    };

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mImageIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        i.setImageResource(mImageIds[position]);
        i.setLayoutParams(new Gallery.LayoutParams(150, 100));
        i.setScaleType(ImageView.ScaleType.FIT_XY);

        return i;
    }
}

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

@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:
                return new DummySectionFragment();
            case 1:
                return new SoundSectionFragment();
            case 2:
                return ps;
        }
        return new DummySectionFragment();
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
        case 0:
            return "Informationen";
        case 1:
            return "Soundboard";
        case 2:
            return "Galerie";
        }
        return null;
    }
}

public static class DummySectionFragment extends Fragment {

    public DummySectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.info, container, false);
    }
}

public static class PicturesSectionFragment extends Fragment {

    public PicturesSectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.pictures, container, false);
    }
}

public static class SoundSectionFragment extends Fragment {

    public SoundSectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sounds, container, false);
    }
}
}

我实际上从你的问题中得到了答案!非常感谢! - edwoollard
4个回答

17

片段(Fragment)没有自己的上下文(Context),它们使用父活动(Activity)的上下文。

  • 要获取父活动的上下文,请使用getActivity()
  • 要使用应用程序上下文,请使用getActivity().getApplicationContext()

尽可能优先使用应用程序上下文。

更新:

getActivity()返回一个 Activity 实例,仅当该片段当前附加到活动中时才成立。


所以,

Fragment f = new MyFragment();  

创建了一个片段,但它尚未附加到活动中。因此,f.getActivity() 返回 null


当它被添加到活动中后:

getFragmentManager().beginTransaction().add(f,"fragment").commit();

现在,getActivity()将返回一个Activity实例。


同样,如果我们将片段从Activity上分离:

getFragmentManager().beginTransaction().detach(f).commit()

getActivity() 方法将再次返回 null 值。


因此,我们不应在 Fragment 类之外使用 getActivity(),因为我们无法确定其是否已附加。因此,我建议您在片段自己的类中的方法(onAttach()onCreate()onActivityCreated())中使用getActivity()


我是这样做的,但它会导致空指针异常:PicturesSectionFragment ps = new PicturesSectionFragment(); 稍后在代码中:new ImageAdapter(ps.getActivity().getApplicationContext()) - bw2801
ps.getActivity() 似乎为空。我记录了它,结果是 null - bw2801
@bw2801 你在错误的位置和错误的时间调用了 getActivity()。请查看更新后的答案。 - S.D.

5
你可以像这样使用
g.setAdapter(new ImageAdapter(getActivity()));

我的意思是,如果你想为ImageAdaptor创建一个新的实例,它需要上下文。如果这样做正确,我的代码将会工作。 - RajaReddy PolamReddy
getActivity() 似乎返回 null。你有任何想法,为什么会这样? - bw2801
1
尝试像这样使用:g.setAdapter(new ImageAdapter(this)); - RajaReddy PolamReddy
1
在你的代码中,你正在将布局附加到选项卡活动上,这是不正确的。你必须将画廊添加到你的一个片段中,它才能正常工作。 - RajaReddy PolamReddy
1
看一下这些例子:http://android.codeandmagic.org/2011/07/android-tabs-with-fragments/,http://neilgoodman.net/2012/03/12/working-with-fragments-on-android-part-2/。 - RajaReddy PolamReddy
显示剩余7条评论

3
从ViewGroup中直接获取上下文是获取我找到的片段上下文最简单、最精确的方法,至少在调用onCreateView方法时,您可以确定不会为getActivity()返回null。
public class Animal extends Fragment {

Context thiscontext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {


     thiscontext = container.getContext();

0
   write under code in Your CoreApplication.java

    step1) 
    public class CoreApplication extends Application {

    private static CoreApplication instance; 
    }

    step2) onCreate(){

    instance = this;

    }



    step3 )
    add under method()

public static CoreApplication getGlobalApplicationContext() {

公共静态方法,返回全局应用程序上下文。
    if (instance == null) {
    throw new IllegalStateException("this application does not 
    inherit GlobalApplication"); " +
    "}

    return instance;
    }

    Step4)
    g.setAdapter(new ImageAdapter(getGlobalApplicationContext()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接