Android - 在寻呼机中获取片段的上下文

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android - 在寻呼机中获取片段的上下文相关的知识,希望对你有一定的参考价值。

我有一个使用寻呼机作为导航的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);
    }
}
}
答案

片段没有自己的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值。


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

另一答案

你可以这样使用

g.setAdapter(new ImageAdapter(getActivity()));
另一答案

获取我发现的片段上下文的最简单,最精确的方法是在调用onCreateView方法时直接从ViewGroup获取它,至少在这里你肯定不会为getActivity()获取null

public class Animal extends Fragment {

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


     thiscontext = container.getContext();
另一答案
   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()));

以上是关于Android - 在寻呼机中获取片段的上下文的主要内容,如果未能解决你的问题,请参考以下文章

当我将片段添加到我的视图寻呼机时(在嵌套滚动视图中),我无法从具有设备后退按钮的应用程序退出

Android如何将listview放入查看寻呼机片段

android寻呼机滑动标签条片段更换器

Android使用片段在viewpager中的页面滚动上放置动画

在android中动态创建选项卡并使用传入的参数加载片段

片段和视图寻呼机