내가 내 앱 의 UI를 업데이트하고 싶습니다. 내 앱이 작동하지 않았지만 이전의 UI로 시도해도 작동합니다. 탭 레이아웃의 경우 하나의 tablayout 활동을 만듭니다. & Weightscale, BP와 맥박 산소 활동 모두 단일 활동을합니다.Android 용 tablayout은 어떻게 사용합니까?
답변
이
public class MainActivity extends TabActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contentReslolver = getContentResolver();
context = getApplicationContext();
// create the TabHost that will contain the Tabs
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
TabSpec deviceTab = tabHost.newTabSpec("First tab");
TabSpec applicationTab = tabHost.newTabSpec("Second tab");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
deviceTab.setIndicator("First");
deviceTab.setContent(new Intent(this, newclass2.class));
applicationTab.setIndicator("second");
applicationTab.setContent(new Intent(this, newclass.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(homeScreenTab);
tabHost.addTab(PeripheralTab);
tabHost.addTab(deviceTab);
tabHost.addTab(applicationTab);
}
좋아하세요 당신은 R.layout.main 될 것
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@android:id/tabhost">
<LinearLayout
android:id="@+id/LinearLayout01"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none" >
<TabWidget
android:id="@android:id/tabs"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
</TabWidget>
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</FrameLayout>
</LinearLayout>
</TabHost>
: 이미 시도한 코드와 동일합니다. .. tablayout을 사용하면 작동하지 않습니다. 내가 간단한 활동 UI로 시도했을 때 작동합니다 :-( – user5506145
탭 xml을 사용하여 문제가 발생한 코드를 공유 할 때까지 Cant 도움말이 표시됩니다. – tanmeet
Plz 위 코드를 확인하십시오. ..Tablayout.java 해당 xml 및 weightsacleActivity.java – user5506145
//Tablayout.java
public class AllDevicesActivity extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
TabHost tabHost = getTabHost();
// Tab for Weighing Scale
TabSpec weighingspec = tabHost.newTabSpec("Weighing Scale");
weighingspec.setIndicator("Weight",
getResources().getDrawable(R.drawable.weighing_icon));
Intent weightIntent = new Intent(this, WeightScaleActivity.class);
weighingspec.setContent(weightIntent);
System.out.println("I am in weightScaleActivity ");
// Tab for BP Monitor
TabSpec bpspec = tabHost.newTabSpec("BP");
// setting Title and Icon for the Tab
bpspec.setIndicator("BP",
getResources().getDrawable(R.drawable.bp_monitor_icon));
Intent bpIntent = new Intent(this, BpActivity.class);
bpspec.setContent(bpIntent);
System.out.println("I am in BpActivity ");
// Tab for Pulse Oximeter
TabSpec pulsespec = tabHost.newTabSpec("Pulse");
pulsespec.setIndicator("Pulse",
getResources().getDrawable(R.drawable.pulse_oxi_icon));
Intent pulseIntent = new Intent(this, PulseOxiActivity.class);
pulsespec.setContent(pulseIntent);
System.out.println("I am in PulseOxiActivity ");
// Tab for All
TabSpec alldevicespec = tabHost.newTabSpec("All");
alldevicespec.setIndicator("All",
getResources().getDrawable(R.drawable.pulse_oxi_icon));
Intent allDeviceIntent = new Intent(this, DashboardActivity.class);
alldevicespec.setContent(allDeviceIntent);
System.out.println("I am in AllDevicesActivity ");
// Adding all TabSpec to TabHost
tabHost.addTab(weighingspec); // Adding Weighing scale tab
tabHost.addTab(bpspec); // Adding Bp monitor tab
tabHost.addTab(pulsespec); // Adding Pulse Oxi tab
tabHost.addTab(alldevicespec); // Adding All Devices tab
}
}
//tabLayout.xml
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="@android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
//WeightscaleActivity
public class WeightScaleActivity extends Activity {
private static final String TAG = "BluetoothHealthActivity";
// Use the appropriate IEEE 11073 data types based on the devices used.
// Below are some examples. Refer to relevant Bluetooth HDP specifications
// for detail.
// 0x1007 - blood pressure meter
// 0x1008 - body thermometer
// 0x100F - body weight scale
private static final int HEALTH_WEIGHTSCALE_PROFILE_SOURCE_DATA_TYPE = 0x100F;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice[] mAllBondedDevices;
private BluetoothDevice mDevice;
private int mDeviceIndex = 0;
private Resources mRes;
private Messenger mHealthService;
private boolean mHealthServiceBound;
private double weight;
private JSONObject jsonObj;
public String weightStr;
public boolean wtConnected = false;
private ProgressDialog progressDialog;
private String healthDeviceMac;
// WeightScale
private TextView weight_scale_value;
private TextView weight_unit;
private Handler mIncomingHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
// Application registration complete.
case BtHealthDeviceService.STATUS_HEALTH_APP_REG:
System.out.println("In hdpacrtivity handleMessage");
break;
// Application unregistration complete.
case BtHealthDeviceService.STATUS_HEALTH_APP_UNREG:
break;
// Reading data from HDP device.
case BtHealthDeviceService.STATUS_READ_DATA:
showIndicator(getResources().getString(
R.string.indicator_start_receive));
break;
// Finish reading data from HDP device.
case BtHealthDeviceService.STATUS_READ_DATA_DONE:
if (weight_scale_value != null) {
weight_scale_value.setText("" + weight);
}
dismissIndicator();
// Send Data on Cloud
sendData();
break;
case BtHealthDeviceService.MSG_MAC_ADDRESS:
System.out.println("msg.obj.toString()" + msg.obj.toString());
System.out.println("In mac address handle" + msg.arg1);
healthDeviceMac = msg.obj.toString();
break;
// Channel creation complete. Some devices will automatically
// establish connection.
case BtHealthDeviceService.STATUS_CREATE_CHANNEL:
Log.d(TAG, "STATUS_CREATE_CHANNEl enabled");
break;
// Channel destroy complete. This happens when either the device
// disconnects or there is extended inactivity.
case BtHealthDeviceService.STATUS_DESTROY_CHANNEL:
break;
case BtHealthDeviceService.RECEIVED_WEIGHT:
int weightt = msg.arg1;
Log.i(TAG, "msg.arg1 @ sys is " + weightt);
String weightStr = "" + weightt/100 + "." + weightt % 100;
weight = Double.parseDouble(weightStr);
System.out.println("Weight is:" + weight);
System.out.println("Weight:******");
break;
default:
super.handleMessage(msg);
}
}
};
private final Messenger mMessenger = new Messenger(mIncomingHandler);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this code is for solving issue
// android.os.NetworkOnMainThreadException
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Check for Bluetooth availability on the Android platform.
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.bluetooth_not_available,
Toast.LENGTH_LONG);
finish();
return;
}
setContentView(R.layout.weightscale_toggle);
mRes = getResources();
mHealthServiceBound = false;
// Weight Scale
// mWeight = (TextView) findViewById(R.id.Weight);
LinearLayout weightLayout = (LinearLayout) findViewById(R.id.value_layout_weight);
weight_scale_value = (TextView) weightLayout
.findViewById(R.id.disp_data_ws_value_textview);
weight_unit = (TextView) weightLayout
.findViewById(R.id.disp_data_ws_unit_textview);
Resources res = getBaseContext().getResources();
weight_unit.setText("Kg");
weight_unit.setText(res.getString(R.string.weightscale_unit));
// Toggle button
final ToggleButton weight_scale_connect_app_button = (ToggleButton) findViewById(R.id.weightscale_register_app_button);
// Initiates application registration through {@link
// BluetoothHDPService}.
// Toggle Button Weightscale
weight_scale_connect_app_button
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean checked) {
if (checked) {
sendMessage(
BtHealthDeviceService.MSG_REG_HEALTH_APP,
HEALTH_WEIGHTSCALE_PROFILE_SOURCE_DATA_TYPE);
System.out.println("in Weight Toggle*****");
} else {
sendMessage(
BtHealthDeviceService.MSG_UNREG_HEALTH_APP,
0);
System.out.println("in unregister Weight Toggle**");
}
}
});
if (weight_scale_connect_app_button.isChecked()) {
sendMessage(BtHealthDeviceService.MSG_REG_HEALTH_APP,
HEALTH_WEIGHTSCALE_PROFILE_SOURCE_DATA_TYPE);
System.out.println("in Weight Toggle**--");
} else {
sendMessage(BtHealthDeviceService.MSG_UNREG_HEALTH_APP, 0);
System.out.println("in unregister Weight Toggle**--");
}
// activity receiver not registered Exception
IntentFilter filter = new IntentFilter();
registerReceiver(mReceiver, filter);
}
// Sets up communication with {@link BluetoothHDPService}.
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mHealthServiceBound = true;
System.out.println("In ServiceConnection onServiceConnected");
Message msg = Message.obtain(null,
BtHealthDeviceService.MSG_REG_CLIENT);
msg.replyTo = mMessenger;
mHealthService = new Messenger(service);
if (mHealthService == null) {
System.out.println(">> mHealthService is null");
}
try {
// 4
System.out.println("in ServiceConnection try...");
mHealthService.send(msg);
} catch (RemoteException e) {
Log.w(TAG, "Unable to register client to service.");
e.printStackTrace();
}
}
public void onServiceDisconnected(ComponentName name) {
System.out.println(" in onServiceDisconnected ");
mHealthService = null;
mHealthServiceBound = false;
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (mHealthServiceBound)
unbindService(mConnection);
unregisterReceiver(mReceiver);
}
@Override
protected void onStart() {
super.onStart();
// If Bluetooth is not on, request that it be enabled.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
initialize();
}
}
/**
* Ensures user has turned on Bluetooth on the Android device.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
initialize();
} else {
finish();
return;
}
}
}
/**
* Used by {@link SelectDeviceDialogFragment} to record the bonded Bluetooth
* device selected by the user.
*
* @param position
* Position of the bonded Bluetooth device in the array.
*/
public void setDevice(int position) {
mDevice = this.mAllBondedDevices[position];
mDeviceIndex = position;
}
private void connectChannel() {
sendMessageWithDevice(BtHealthDeviceService.MSG_CONNECT_CHANNEL);
}
private void disconnectChannel() {
sendMessageWithDevice(BtHealthDeviceService.MSG_DISCONNECT_CHANNEL);
}
private void initialize() {
// Starts health service.
Intent intent = new Intent(this, BtHealthDeviceService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
// Intent filter and broadcast receive to handle Bluetooth on event.
private IntentFilter initIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
return filter;
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR) == BluetoothAdapter.STATE_ON) {
initialize();
}
}
}
};
// Sends a message to {@link BluetoothHDPService}.
private void sendMessage(int what, int value) {
if (mHealthService == null) {
System.out
.println("In HDP activity sendMessage -Health Service not connected.");
Log.d(TAG, "Health Service not connected.");
return;
}
try {
System.out.println("hdp activity send message");
System.out.println("what******" + what);
System.out.println("value*****" + value);
mHealthService.send(Message.obtain(null, what, value, 0));
} catch (RemoteException e) {
Log.w(TAG, "Unable to reach service.");
e.printStackTrace();
}
}
// Sends an update message, along with an HDP BluetoothDevice object, to
// {@link BluetoothHDPService}. The BluetoothDevice object is needed by the
// channel creation
// method.
private void sendMessageWithDevice(int what) {
if (mHealthService == null) {
Log.d(TAG, "Health Service not connected.");
System.out.println("in sendMessageWithDevice");
return;
}
try {
System.out.println("in sendMessageWithDevice try");
mHealthService.send(Message.obtain(null, what, mDevice));
} catch (RemoteException e) {
Log.w(TAG, "Unable to reach service.");
e.printStackTrace();
}
}
/**
* Dialog to display a list of bonded Bluetooth devices for user to select
* from. This is needed only for channel connection initiated from the
* application.
*/
public static class SelectDeviceDialogFragment extends DialogFragment {
public static SelectDeviceDialogFragment newInstance(String[] names,
int position) {
SelectDeviceDialogFragment frag = new SelectDeviceDialogFragment();
Bundle args = new Bundle();
args.putStringArray("names", names);
args.putInt("position", position);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] deviceNames = getArguments().getStringArray("names");
int position = getArguments().getInt("position", -1);
if (position == -1)
position = 0;
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.select_device)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
((WeightScaleActivity) getActivity())
.connectChannel();
}
})
.setSingleChoiceItems(deviceNames, position,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
((WeightScaleActivity) getActivity())
.setDevice(which);
}
}).create();
}
}
private void sendData() {
jsonObj = new JSONObject();
new RestConnection().execute();
}
private class RestConnection extends AsyncTask<Void, Void, String> {
private String TAG = this.getClass().getName();
ProgressDialog progressDialog;
public RestConnection() {
super();
}
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(Void... arg0) {
String st = jsonObj.toString();
String response = "";
Log.i(TAG, st);
JSONObject item = null;
try {
item = new JSONObject(st);
} catch (JSONException e) {
Log.e(TAG, "Could not parse malformed JSON:" + st);
}
if (item == null) {
Log.e(TAG, "Null");
}
// doing the respective post
try {
// POST DATA
String url = Constants.getDataPost();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpConnectionParams.setConnectionTimeout(
httpClient.getParams(), 10000);
JSONObject json = new JSONObject();
json.put("siteId", "");
if (wtConnected == true) {
json.put("patientId", 5);
json.put("deviceMACId", healthDeviceMac);
json.put("readingType", 103);
json.put("deviceData", Double.toString(weight));
json.put("deviceType", "WeightScale");
}
json.put("assetId", "");
json.put("geoLocationLatitude", "");
json.put("clientId", "");
json.put("timeStamp", System.currentTimeMillis());
json.put("deviceRawData", "");
json.put("geoLocationLongitude", "");
System.out.println("Json Is:" + json);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.i(TAG, "response "
+ httpResponse.getStatusLine().getStatusCode());
HttpEntity entityPost = httpResponse.getEntity();
InputStream is = entityPost.getContent();
String response1 = convertStreamToString(is);
Log.i(TAG, "response message " + response1);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Post error:Error");
Log.i(TAG, "Weight" + response);
}
return response;
}
@Override
protected void onPostExecute(String result) {
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
// Progress Dialog for Data Reading
private Dialog progress;
private void showIndicator(String message) {
if (progress == null) {
progress = new Dialog(WeightScaleActivity.this);
// AlertDialog.Builder builder = new AlertDialog.Builder(context);
progress.getWindow().setBackgroundDrawable(new ColorDrawable(0));
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.setContentView(R.layout.custom_alert);
progress.setCancelable(false);
}
setIndicatorMessage(message);
if (!progress.isShowing()) {
progress.show();
}
}
private void setIndicatorMessage(String message) {
if (progress == null) {
return;
}
TextView syncMessages = (TextView) progress
.findViewById(R.id.syncMessages1);
if (message == null) {
message = "";
}
if (syncMessages != null) {
syncMessages.setText(message);
}
}
private void dismissIndicator() {
if (progress == null) {
return;
}
progress.dismiss();
progress = null;
}
// Are you sure you want to exit? Alert Box
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
WeightScaleActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
- 1. Android Accelerometer는 어떻게 사용합니까?
- 2. Android ZoomButtonsController는 어떻게 사용합니까?
- 3. 어떻게 리눅스 용 디버거를 사용합니까
- 4. TabLayout은 이전 어댑터의 프래그먼트를 유지합니다.
- 5. Android BrowserFrame이란 무엇이며 어떻게 사용합니까?
- 6. Android Studio에서 appengineEndpointsGetClientLibs를 어떻게 사용합니까?
- 7. Android Geofencing API는 어떻게 사용합니까?
- 8. Java 용 Netbeans에서는 API를 어떻게 사용합니까?
- 9. i18n 용 Codeigniter에서 Gettext 라이브러리를 어떻게 사용합니까?
- 10. iphone 용 opengles에서 glBindTexture를 어떻게 사용합니까?
- 11. clang 용 사용자 정의 어셈블러는 어떻게 사용합니까?
- 12. 루비 용 자외선 + 텍스트 메이트? 어떻게 사용합니까?
- 13. 어떻게 다트 용 폴리머를 자바 스크립트로 사용합니까?
- 14. Android 용 모노 용 Xamarin 디자이너는 어떤 테마를 사용합니까?
- 15. Android 액션 바 스타일 생성기는 어떻게 사용합니까?
- 16. 이 Android 에뮬레이터 버그 패치는 어떻게 사용합니까?
- 17. Android HTTPPOST jpeg를 장고 서버에 어떻게 사용합니까?
- 18. Android Java 코드에서 CordovaActivity와 AppCompatActivity를 어떻게 사용합니까?
- 19. Android 용 OpenJPEG 빌드
- 20. Android 용 모노 - 어떻게 작동합니까?
- 21. android에서 persist.img를 어떻게 사용합니까?
- 22. Android에서 sharedPreferences는 어떻게 사용합니까?
- 23. 앱이 sqlite를 어떻게 사용합니까?
- 24. Eclipse에서 MATLAB은 어떻게 사용합니까?
- 25. BigInt 라이브러리는 어떻게 사용합니까?
- 26. WhiteRaccoon 어떻게 사용합니까?
- 27. chrome.tabs.onUpdated.addListener는 어떻게 사용합니까?
- 28. laravel에서 filemaker를 어떻게 사용합니까?
- 29. MapStateListener는 어떻게 사용합니까?
- 30. 어떻게 통역사가 DSL을 사용합니까?
여기에 코드를 게시하십시오 –
질문이 너무 짧거나 누락 된 코드라는 메시지가 표시되면 질문의 반이 반복되지 않음을 의미하지 않습니다. –
크리켓 -007 : 실수로 죄송합니다 ... – user5506145