【问题标题】:Passing a Listener Event To a SlidingTabLayout将侦听器事件传递给 SlidingTabLayout
【发布时间】:2015-12-07 01:52:58
【问题描述】:

我已经搜索了很多关于如何使用SlidingTabLayout 在片段之间进行通信的内容,但还没有真正得到一个好的答案。 (尽管我仍然对 android 不熟悉)我认为我离解决方案不太远 - 任何帮助将不胜感激。目前正在制作一个计步器项目,我正在尝试在检测到步骤时更新SlidingTabLayout 中的TextView。我有一个 StepListener 接口,当检测到 Step 时会收到通知,我认为我的 Tabs 可以简单地实现该接口并收到通知,从而在我进行时增加我的 TextView 但没有成功。

我试过this。当 debuggin 注意到它到达 Tab1 中的 stepsChanged 方法但随后应用程序崩溃。任何帮助表示赞赏。

我的 MainActivity....

public class PedometerActivity extends ActionBarActivity implements StepListener, ServiceConnection {

    // applying buissness rules
    public static final int DAILY_GOAL = 10000;

    public float currentSteps;


    // Declaring Your View and Variables for the UI
    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[] = {"Home", "MyStats"};
    int Numboftabs = 2;

    //declaring Variables for acess to Db and Prefs
    UserLocalStore userLocalStore;
    SharedPreferences sharedPreferences;

    //declaring variables for the Step\Service
    private StepService mStepService = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pedometer);
        userLocalStore = new UserLocalStore(this);

        this.startStepService();
        this.bindStepService();

       /* sharedPreferences = getSharedPreferences("steps", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("currentSteps", numSteps); TODO remove this
        editor.commit();*/

        // Creating The Toolbar and setting it as the Toolbar for the activity
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });


        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);


    }

    @Override
    public void stepsChanged(float numSteps) {


        //TODO /////

        for (int loop = 0; loop < adapter.getCount(); loop++) {

            if (adapter.getItem(0) instanceof StepListener) {
                ((StepListener) adapter.getItem(0)).stepsChanged(numSteps);
            }//end of if
        }// end of for loop

    }

    public float getCurrentSteps(float currentSteps) {

        return currentSteps;

    }


    /**
     * currently unused....code
     *
     * @return
     */
    private boolean authenticate() {
        return userLocalStore.getUserLoggedIn();
    }

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


    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    private void startStepService() {
        this.startService(new Intent(PedometerActivity.this, StepService.class));

    }

    /**
     * binds Pedometer Activity to the Service class
     * (I.e this service is going to communicate to this Activity)
     * must implement the ServiceConnection interface here
     */
    private void bindStepService() {
        this.bindService(new Intent(PedometerActivity.this, StepService.class),
                this, Context.BIND_AUTO_CREATE + Context.BIND_DEBUG_UNBIND);

    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        mStepService = ((StepService.StepBinder) iBinder).getService();
        mStepService.registerStepListener(this);

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }


}

我的 Tab1....

public class Tab1 extends Fragment implements StepListener {

    private static final int DAILY_GOAL = 10000;

    UserLocalStore userLocalStore;

    TextView tvStepValue;

    //float currentSteps;

    Database db;

    private Activity activity;
    private PieChart mPieChart;
    private PieModel sliceGoal, sliceCurrent;

    StepCounter mStepCounter;


    public Tab1() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_1, container, false);


        tvStepValue = (TextView) v.findViewById(R.id.tvStepValue);


        // mPieChart = (PieChart) v.findViewById(R.id.piechart);
        // load data to PieCHart

        return v;
    }

    /**
     * method needed in Order to give the fragment a context to be used in conjunction with SharedPref/Database
     *
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        this.activity = activity;
        super.onAttach(activity);
    }

    private void loadData(View v) {


    }


    @Override
    public void stepsChanged(float numSteps) {
        tvStepValue.setText(String.valueOf(numSteps));
    }


}

应用崩溃时我的错误消息....

   09-10 17:21:29.748  26336-26336/com.example.calum.myslidingtablayout E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.example.calum.myslidingtablayout.Tab1.stepsChanged(Tab1.java:81)
        at com.example.calum.myslidingtablayout.PedometerActivity.stepsChanged(PedometerActivity.java:100)
        at com.example.calum.myslidingtablayout.StepCounter.onSensorChanged(StepCounter.java:50)
        at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:250)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4867)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
        at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

    标签: android listener


    【解决方案1】:

    一旦你习惯了,片段之间的通信就很简单了。 在Tab 1 中,您需要设置接口并将其链接到PedometerActivity 类。Google explains how to preform fragment communications via interface

    简而言之,您最终会在 Fragment 的 onAttach 中得到类似的内容 mCallback = (PedometerActivity) 活动;

    或者,您可以使用更易于使用且功能更丰富的库。 Otto 是来自 square 的库,你可以把它想象成一个通用接口。您不必在任何地方注册接口,您将 Post 您的数据和您定义的 Subscribe 方法将以您想要的任何方式接收和处理数据。您可以使用Otto 在片段、活动、类等之间进行通信。我强烈建议您检查一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      相关资源
      最近更新 更多