选项卡式活动:从imageview获取图像时出现问题

时间:2016-03-29 07:13:52

标签: java android

我在选项卡式活动中从我的图像视图中获取图像时遇到问题。我的标签式活动包含365个页面,每个页面上都有一个图像。现在我有一个按钮,用于将图像作为文件保存到内部存储器。但每当我按下该按钮时,它都会保存上一页的图像,因此不是当前聚焦的图像。

以下是保存图片的代码:

ImageView imageView;
            imageView = (ImageView) mViewPager.findViewById(R.id.imageView);
            Bitmap pictureBitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

            String filename = dates[mViewPager.getCurrentItem() + 1];
            Log.d("saved date:", dates[mViewPager.getCurrentItem() + 1]);
            File file = new File(getApplicationContext().getFilesDir(), "test");

            FileOutputStream outputStream;

            try {
                outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
                pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

更新:

以下是来自PlaceholderFragment类的onCreateView的代码:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Log.d("LOADING IMAGE:", String.valueOf(imgs[getArguments().getInt(ARG_SECTION_NUMBER)]));
        ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
        imageView.setImageResource(imgs[getArguments().getInt(ARG_SECTION_NUMBER)]);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(dates[getArguments().getInt(ARG_SECTION_NUMBER)]);
        TextView weekNumber = (TextView) rootView.findViewById(R.id.weekNumber);
        weekNumber.setText("Week " + weekNumbers[getArguments().getInt(ARG_SECTION_NUMBER)]);



        FloatingActionButton fab4 = (FloatingActionButton) rootView.findViewById(R.id.fab4);
        fab4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("FAB4", "CLICK");
                Utilities util = new Utilities();
                util.saveImage(rootView, getArguments().getInt(ARG_SECTION_NUMBER),dates, getContext());
            }
        });

以下是我util班的代码:

public class Utilities {
public void saveImage(View rootView, int pageNumber, String[] dates, Context context){
    ImageView imageView;
    imageView = (ImageView) rootView.findViewById(R.id.imageView);
    Bitmap pictureBitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

    String filename = dates[pageNumber];
    Log.d("saved date:", dates[pageNumber]);
    //File file = new File(getApplicationContext().getFilesDir(), "test");

    FileOutputStream outputStream;

    try {
        outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我的fragment_main.xml:

<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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="example.test.sliderappv002.MainActivity$PlaceholderFragment">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:layout_centerHorizontal="true"
        android:text="placeholderDay"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/weekNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/section_label"
        android:layout_centerHorizontal="true"
        android:text="placeholderWeek" />

</RelativeLayout>

我的LogCat输出:


03-29 09:42:17.597 6343-6343/example.test.sliderappv002 E/AndroidRuntime: FATAL EXCEPTION: main
Process: example.test.sliderappv002, PID: 6343
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at example.test.sliderappv002.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:323)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18794)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

如果您使用PagerAdapter - 只需在instantiateItem()方法中设置按钮单击侦听器。

如果您正在使用FragmentPagerAdapter,请在Fragment#onCreateView()

中返回的片段的FragmentPagerAdapter#getItem()方法中设置按钮监听器

代码段:

public static class YourAdapter extends FragmentPagerAdapter {
    ...

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

public static class YourFragment extends Fragment {

...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         ...
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //save image code goes here
            }
        });
    }
}

<强>更新: 之前的解决方案假设您在片段布局中有一个FAB,但看起来您在活动布局中只定义了一个FloatingActionButton ...在这种情况下,从当前片段获取ImageView的最简单方法是像这样

View rootview = ((Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, mViewPager.getCurrentItem())).getView();
if (rootView != null)
    ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);

可能不是最干净的解决方案,但它是一种解决方案。