【问题标题】:How to send the right context to the new object如何将正确的上下文发送到新对象
【发布时间】:2014-05-18 12:55:30
【问题描述】:

我有公共类 PageFragment,它扩展了 Fragment 以创建 6 个页面,其中的视图由另一个类填充。 下面是 PageFragment 类:

public class PageFragment extends Fragment {
static final String arg_page_number = "arg_page_number";

int pageNumber;
int backColor;
public LinearLayout framesContainer;
ExecutorService ex = Executors.newCachedThreadPool();
Future<ArrayList<ElementData>> s = ex.submit(new MyThread());

public static PageFragment newInstance(int page) {
    PageFragment pageFragment = new PageFragment();
    Bundle arguments = new Bundle();
    arguments.putInt(arg_page_number, page);
    pageFragment.setArguments(arguments);
    return pageFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pageNumber = getArguments().getInt(arg_page_number);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.table_row, null);
    framesContainer = (LinearLayout) view.findViewById(R.id.frames_container);
    for (int i = 0; i < 20; i += 4) {
        Frame frame = new Frame(getApplicationContext());
        try {
            frame.setStudyName(s.get().get(0).Days().get(i));
            frame.setStudyKindName(s.get().get(0).Days().get(i + 1));
            frame.setAuditorium(s.get().get(0).Days().get(i + 2));
            frame.setLectureTitle(s.get().get(0).Days().get(i + 3));
            framesContainer.addView(frame);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    return view;
}

class MyThread implements Callable<ArrayList<ElementData>> {
    public ArrayList<ElementData> call() {
        ArrayList<ElementData> elementDataArrayList = Parser.parse("url");
        return elementDataArrayList;
    }
}}

这是我的活动:

public class MyActivity extends FragmentActivity {
/**
 * Called when the activity is first created.
 */
static final String TAG = "myLogs";
static final int PAGE_COUNT = 6;
ViewPager pager;
PagerAdapter pagerAdapter;
SharedPreferences sPref;
String[] groups = {....};
final String SAVED_TEXT = "SavePref";
private LinearLayout framesContainer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sPref = getPreferences(MODE_PRIVATE);
    if (sPref.getBoolean(SAVED_TEXT, true)) {
        setContentView(R.layout.startpage);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, groups);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        Spinner spinner = (Spinner)findViewById(R.id.spinner);
        spinner.setAdapter(adapter);

        final int selectionCurrent = spinner.getSelectedItemPosition();
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                if (selectionCurrent != position) {
                    sPref = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor ed = sPref.edit();
                    ed.putBoolean(SAVED_TEXT, false);
                    ed.commit();
                    setContentView(R.layout.main);


                    pager = (ViewPager) findViewById(R.id.frames_container);
                    pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
                    pager.setAdapter(pagerAdapter);

                    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            Log.d(TAG, "onPageSelected, position = " + position);

                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {

            }
        });
    } else {
        setContentView(R.layout.main);
        pager = (ViewPager) findViewById(R.id.frames_container);
        pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);

        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.d(TAG, "onPageSelected, position = " + position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position);
    }

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

当我使用 getApplicationContext 时,会显示未解决方法的错误。 我需要在这里转换 MyActivity 的上下文吗?我该怎么做?

框架类:

public class Frame extends RelativeLayout {
    private TextView StudyName;
    private TextView Auditorium;
    private TextView StudyKindName;
    private TextView LectureTitle;

    public Frame(Context context) {
        super(context);
        initComponent();
    }

    private void initComponent() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.table_row, this);
        StudyName = (TextView) findViewById(R.id.StudyName);
        Auditorium = (TextView) findViewById(R.id.Auditorium);
        StudyKindName = (TextView) findViewById(R.id.StudyKindName);
        LectureTitle = (TextView) findViewById(R.id.LectureTitle);
    }

    public void setStudyName(String study_Name) {
        StudyName.setText(study_Name);
    }

    public void setAuditorium(String auditorium) {
        Auditorium.setText(auditorium);
    }

    public void setStudyKindName(String studyKindName) {
        StudyKindName.setText(studyKindName);
    }

    public void setLectureTitle(String lectureTitle) {
        LectureTitle.setText(lectureTitle);
    }

}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/frames_container"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/program_frame"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="5dip">

    <TextView
        android:id="@+id/StudyName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/white"
        android:textStyle="normal"
        android:textSize="16sp"
        android:text="StudyName"/>
    <TextView
        android:id="@+id/Auditorium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:textColor="@android:color/darker_gray"
        android:textStyle="bold"
        android:textSize="16sp"
        android:singleLine="true"
        android:text="Auditorium"/>
    <TextView
        android:id="@+id/StudyKindName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/StudyName"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dip"
        android:textColor="@android:color/darker_gray"
        android:textStyle="bold"
        android:textSize="15sp"
        android:singleLine="true"
        android:text="StudyKindName"/>
    <TextView
        android:id="@+id/LectureTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/StudyKindName"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dip"
        android:textColor="@android:color/darker_gray"
        android:textStyle="normal"
        android:textSize="12sp"
        android:text="Lector"/>
    <ImageView
        android:id="@+id/imageView2"
        android:layout_below="@id/LectureTitle"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="15dip"
        android:background="#bb333333" />
</RelativeLayout>

【问题讨论】:

  • 你可以减少不相关的代码。并指出出现问题的行
  • 您应该针对新问题发布新问题。这完全改变了我回答的问题,这是不正确的。视图寻呼机处于活动布局中

标签: java android


【解决方案1】:

您可以在 Fragment 中使用getActivity().getApplicationContext()

我不知道FrameFrame frame = new Frame(getApplicationContext()); 中是什么。如果您正在做 ui 的事情,请仅使用 getActivity()

阅读

When to call activity context OR application context?

【讨论】:

  • 呃,好像我急于结束这个话题。我在主题中添加了 Frame 类。现在我在 framesContainer.addView(frame) 中得到 NullPointerException,看起来它没有将数据设置为 TextViews。
  • framesContainer 为空。一个新问题发布了一个新线程。一个线程解决不了所有问题
  • 谢谢,对不起。将尝试找出为什么它为空。
  • 检查 id frames_container @ framesContainer = (LinearLayout) view.findViewById(R.id.frames_container);。在xml布局中是否也一样
  • 对于视图使用getActivity()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
相关资源
最近更新 更多