findViewById无法解析方法

时间:2016-08-23 18:19:16

标签: java android

我尝试使用像here这样的文本视图,但我总是得到findById的错误“无法解决方法”。我想通了,这是因为我的类没有扩展类Activity,但我不知道热修复它。 getActivity()前面的setContenviewgetView中的onCreate仅在我第一次构建应用时工作。 有没有一种简单的方法在textview中显示字符串和整数?

我的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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mbientlab.metawear.starter.DeviceSetupActivityFragment"
    tools:showIn="@layout/activity_device_setup">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sync"
        android:id="@+id/acc_start"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="reset"
        android:id="@+id/acc_stop"
        android:layout_below="@+id/acc_start"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="59dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Steps: 0"
        android:id="@+id/stepView"
        android:layout_below="@+id/acc_stop"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="118dp" />

</RelativeLayout>

我的代码:

package com.mbientlab.metawear.starter;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Bundle;
import android.view.ViewGroup;
import android.util.Log;
import android.widget.TextView;


import com.mbientlab.metawear.MetaWearBleService;
import com.mbientlab.metawear.MetaWearBoard;
import com.mbientlab.metawear.data.CartesianFloat;
import com.mbientlab.metawear.AsyncOperation;
import com.mbientlab.metawear.module.Gpio;
import com.mbientlab.metawear.module.Timer;
import com.mbientlab.metawear.Message;
import com.mbientlab.metawear.RouteManager;
import static com.mbientlab.metawear.MetaWearBoard.ConnectionStateHandler;
import static com.mbientlab.metawear.AsyncOperation.CompletionHandler;

import com.mbientlab.metawear.UnsupportedModuleException;
import com.mbientlab.metawear.module.Bmi160Accelerometer;

/**
 * A placeholder fragment containing a simple view.
 */
public class DeviceSetupActivityFragment extends Fragment implements ServiceConnection {

    //private MetaWearBoard mwBoard;
    public Bmi160Accelerometer accModule;

    TextView counted_steps; //for showing the steps in the textview


    public interface FragmentSettings {
        BluetoothDevice getBtDevice();
    }

    private MetaWearBoard mwBoard= null;
    private FragmentSettings settings;

    public DeviceSetupActivityFragment() {
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.acc_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                accModule.readStepCounter(false);

            }
        });
        view.findViewById(R.id.acc_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                accModule.resetStepCounter();
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       setContentView(R.layout.fragment_device_setup);
       counted_steps = (TextView) findViewById(R.id.stepView);

        Activity owner = getActivity();
        if (!(owner instanceof FragmentSettings)) {
            throw new ClassCastException("Owning activity must implement the FragmentSettings interface");
        }

        settings = (FragmentSettings) owner;
        owner.getApplicationContext().bindService(new Intent(owner, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        ///< Unbind the service when the activity is destroyed
        getActivity().getApplicationContext().unbindService(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setRetainInstance(true);
        return inflater.inflate(R.layout.fragment_device_setup, container, false);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mwBoard= ((MetaWearBleService.LocalBinder) service).getMetaWearBoard(settings.getBtDevice());

        ready();

        // Route data from the chip's step counter
        accModule.routeData().fromStepCounter(false).stream("step_counter").commit()        
                .onComplete(new CompletionHandler<RouteManager>() {
                    @Override
                    public void success(RouteManager result) {
                        result.subscribe("step_counter", new RouteManager.MessageHandler() {
                            @Override
                            public void process(Message msg) {
                                Log.i("MainActivity", "Steps= " + msg.getData(Integer.class));
                                counted_steps.setText("Steps: " + msg.getData(Integer.class));
                            }
                        });
                    }
                });

        accModule.start();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    /**
     * Called when the app has reconnected to the board
     */
    public void reconnected() { }

    /**
     * Called when the mwBoard field is ready to be used
     */
    public void ready() {
        try {
            accModule = mwBoard.getModule(Bmi160Accelerometer.class);

            accModule.configureStepDetection()

                    .setSensitivity(Bmi160Accelerometer.StepSensitivity.NORMAL)
                            // Enable step counter
                    .enableStepCounter()
                    .commit();


        }  catch (UnsupportedModuleException e) {
            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

  

我总是收到findById的错误“无法解决方法”。我想通了,因为我的班级没有扩展班级Activity

是的,您正在使用Fragment ...

  

getActivity()前面的setContentViewgetView中的onCreate仅在我第一次构建应用时才有效。

你可能甚至不应该使用片段的onCreate方法。当该代码实际上可以在Activity类中时,至少不要修改Activity的状态。例如,Fragment不应该更改Activity的内容视图。

用于片段的大部分代码都可以放在onCreateView(这是一个可以使用findViewById的地方),这会导致......

  

是否有一种在textview中显示字符串和整数的简单方法?

是的,有很多地方可以做到。例如,您可以使用view.findViewById方法中的onViewCreatedTextView中使用的布局文件获取和设置各自的onCreateView