问题
I'm doing my project for getting data by acceleometer sensor in android platform. I'm having error codes in the 3 last line codes. Exactly the error is the findViewById is not for get data fragment. so, how I can use findviewbyId in Fragment for getting data accelerometer sensor?many thanks for the answer :)
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);
}
回答1:
You must inflate your Views
in 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;
}
Hope this helps.
来源:https://stackoverflow.com/questions/14919182/the-method-findviewbyidint-is-undefined-for-the-type-get-data-fragment-for-acc