如何在ViewPager片段之间共享数据?

时间:2015-04-11 07:47:04

标签: android

我刚开始使用android编程,因此我的代码看起来很难看。它是从各种教程拼凑而成的,几乎可以满足我的需要。快速解释我需要做什么:

我有两个标签的活动。一个选项卡在整个屏幕上实现OnClickListener,每次单击屏幕时都会递增计数器。如果屏幕从上到下,或从下到上滑动,该计数器将重置为0.现在,我一直在努力:当我滑动到下一个选项卡时,我希望该计数器的当前值为传递到下一个片段,用于计算。

有人可以帮助我吗?

我也很乐意接受任何有助于我清理现有代码的评论。

干杯

这是我目前的代码:

主要活动的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <de.regenistdoof.sporecounter.SlidingTabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>

主要活动:

package de.regenistdoof.sporecounter;

import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends FragmentActivity {

    ViewPager viewPager;


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

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
                MainActivity.this));



        // Give the SlidingTabLayout the ViewPager
        SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        // Center the tabs in the layout
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setViewPager(viewPager);
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

Counter Fragment&x; xml:

<?xml version="1.0" encoding="utf-8"?>
<!-- This is the fragment  to be displayed for a section associated with a tab -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout">

    <TextView
        android:id="@+id/counter"
        android:text="@string/counter_default"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center_horizontal"
        android:textSize="50sp" />


</LinearLayout>

Counter Fragment代码:

package de.regenistdoof.sporecounter;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

// In this case, the fragment displays simple text based on the page
public class FragmentCounter extends Fragment implements View.OnClickListener,GestureDetector.OnGestureListener{

int count = 0;
TextView counter;
LinearLayout layout;
View view;
boolean swipe = false;
String TAG = "sporecounter";



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

        view = inflater.inflate(R.layout.fragment_counter, container, false);

        layout = (LinearLayout) view.findViewById(R.id.layout);
        layout.setOnClickListener(this);

        counter = (TextView) view.findViewById(R.id.counter);

        final GestureDetector gesture = new GestureDetector(getActivity(),
                new GestureDetector.SimpleOnGestureListener() {


                    @Override
                    public boolean onSingleTapUp(MotionEvent e) {

                        return false;
                    }

                    @Override
                    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                           float velocityY) {

                        final int SWIPE_MIN_DISTANCE = 300;

                        try {
                            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MIN_DISTANCE && e1.getY() > e2.getY()){
                                Log.d(TAG, "swipe up");
                                count = 0;
                                swipe = true;
                                counter.setText(Integer.toString(count));
                            }
                            else if ((Math.abs(e1.getY() - e2.getY()) > SWIPE_MIN_DISTANCE && e2.getY() > e1.getY())){
                                Log.d(TAG, "swipe down");
                                count = 0;
                                swipe = true;
                                counter.setText(Integer.toString(count));
                            }

                        } catch (Exception e) {
                            // nothing
                        }
                        return super.onFling(e1, e2, velocityX, velocityY);
                    }
                });

        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gesture.onTouchEvent(event);
            }
        });


        return view;
    }

    @Override
    public void onClick(View v) {

         if (swipe) {
             counter.setText("0");
             swipe = false;
         } else {
             count++;
             counter.setText(Integer.toString(count));
         }
     }


    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }
}

编辑:

这些是使解决方案适用于我的代码的重要部分:

这个想法是:FragmentCounter增加反击 - &gt;在MainActivity中设置值 - &gt; MainActivity在FragmentCalculations中调用updateCall方法 - &gt; FragmentCalculations更新textview。

主要活动:

private FragmentCalculations fragcalc;

    // get latest count from FragmentCounter and call updateCall method in FragmentCalculations
    public void setLastCount(int count) {
        ((FragmentCalculations)fragcalc).updateCall(count);
    }

FragmentCounter: 这段代码进入了我用来递增计数器的按钮的onclicklistener:

((MainActivity)getActivity()).setLastCount(count);

FragmentCalculations:

public class FragmentCalculations extends Fragment{

public static EditText numberOfSquaresRef, countedCellsRef;

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_calculation, container, false);

    countedCellsRef = (EditText) view.findViewById(R.id.counted_cells);

 public void updateCall(int count){
    Log.d(TAG, "fragcalc value: " + count);
    countedCellsRef.setText(""+count);
}

1 个答案:

答案 0 :(得分:0)

您可以将最后一个值存储在MainActivtiy中。

示例:

在MainActivity中:

private int lastCount;

public int getLastCount() {
    return this.lastCount;
}

public void setLastCount(int newValue) {
    this.lastCount = newValue;
}

在你的片段中:

//Set the value:
((MainActivity) getActivity()).setLastCount(999);

//Get the value:
int lastCount = ((MainActivity) getActivity()).getLastCount();