我正在做我在Android平台上通过加速度计传感器获取数据的项目.我在最后3行代码中有错误代码.确切的错误是findViewById不是用于获取数据片段.那么,我如何在Fragment中使用findviewbyId来获取数据加速计传感器?非常感谢答案:)
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
public class GetDataFragment extends Fragment implements SensorEventListener {
//definisi variabel-variabel
//Sensor accelerometer;
private Activity parent;
TextView koordinatX;
TextView koordinatY;
TextView koordinatZ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.get_data, container, false);
}
private SensorManager sensorManager;
private Sensor sensor;
//TextView koordinatX;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
parent = getActivity();
sensorManager = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
koordinatX = (TextView)findViewById(R.id.coordinatx);
koordinatY = (TextView)findViewById(R.id.coordinaty);
koordinatZ = (TextView)findViewById(R.id.coordinatz);
}
解决方法:
您必须在onCreateView()中膨胀您的视图:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.get_data, container, false);
koordinatX = (TextView)rootView.findViewById(R.id.coordinatx);
koordinatY = (TextView)rootView.findViewById(R.id.coordinaty);
koordinatZ = (TextView)rootView.findViewById(R.id.coordinatz);
return rootView;
}
希望这可以帮助.