5

ページャーをナビゲーションとして使用するAndroidアプリケーションがあります。タブには、コンテンツとして 3 つのレイアウトがあります。フラグメントの 1 つにギャラリーがあり、画像を追加したいと考えています。そのためには 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 にコンテキストを与える必要があります。しかし、そこにどのようなコンテキストを設定する必要がありますか?

編集:これは私の完全なコードです:

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

4 に答える 4

17

フラグメントには独自のコンテキストがなく、親アクティビティを使用します。

  • 親アクティビティ コンテキストを取得するには、次を使用します。getActivity()
  • アプリケーション コンテキストを使用するには、次を使用します。getActivity().getApplicationContext()

可能な限りアプリケーション コンテキストを優先します。

アップデート:

getActivity()Fragment の は、その Fragment が現在 Activity にアタッチされている場合に限り、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()

于 2013-04-06T08:57:29.930 に答える
5

あなたはこのように使うことができます

g.setAdapter(new ImageAdapter(getActivity()));
于 2013-04-06T08:49:42.133 に答える