Example usage for android.widget LinearLayout addView

List of usage examples for android.widget LinearLayout addView

Introduction

In this page you can find the example usage for android.widget LinearLayout addView.

Prototype

public void addView(View child) 

Source Link

Document

Adds a child view.

Usage

From source file:com.kyakujin.android.autoeco.ui.MainActivity.java

/**
 * AdView/*from w w w .java 2s  .  co m*/
 */
private void addAD() {
    // for adView
    //
    adView = new AdView(this, AdSize.BANNER, Conf.MY_AD_UNIT_ID);

    LinearLayout layout = (LinearLayout) findViewById(R.id.admobspace);

    // adView? --- ???
    layout.addView(adView);

    // ???
    AdRequest adRequest = new AdRequest();
    if (BuildConfig.DEBUG) {
        // ??? - ?????
        // 
        adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
        // Android
        // "XXXXXX...XX"????ID(??ID???????)
        adRequest.addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        // ????
    }
    adView.loadAd(adRequest);
    // adView? --- ????

}

From source file:com.microsoft.live.sample.hotmail.ContactsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_contacts);

    ListView lv = getListView();// w w  w  . j  a  v a2 s .  c  om
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Contact contact = (Contact) parent.getItemAtPosition(position);
            ViewContactDialog dialog = new ViewContactDialog(ContactsActivity.this, contact);
            dialog.setOwnerActivity(ContactsActivity.this);
            dialog.show();
        }
    });

    LinearLayout layout = new LinearLayout(this);
    Button newCalendarButton = new Button(this);
    newCalendarButton.setText("New Contact");
    newCalendarButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            CreateContactDialog dialog = new CreateContactDialog(ContactsActivity.this);
            dialog.setOwnerActivity(ContactsActivity.this);
            dialog.show();
        }
    });

    layout.addView(newCalendarButton);
    lv.addHeaderView(layout);

    mAdapter = new ContactsListAdapter(this);
    setListAdapter(mAdapter);

    LiveSdkSampleApplication app = (LiveSdkSampleApplication) getApplication();
    mClient = app.getConnectClient();
}

From source file:com.mikecorrigan.trainscorekeeper.FragmentButton.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.vc(VERBOSE, TAG, "onCreateView: inflater=" + inflater + ", container=" + container
            + ", savedInstanceState=" + Utils.bundleToString(savedInstanceState));

    View rootView = inflater.inflate(R.layout.fragment_button, container, false);

    Bundle args = getArguments();/*from ww  w  .  j  a  v  a  2  s. c o m*/
    if (args == null) {
        Log.e(TAG, "onCreateView: missing arguments");
        return rootView;
    }

    // The activity must support a standard OnClickListener.
    final MainActivity mainActivity = (MainActivity) getActivity();
    final Context context = mainActivity;

    players = mainActivity.getPlayers();
    if (players != null) {
        players.addListener(mPlayersListener);
    }

    // final int index = args.getInt(ARG_INDEX);
    final String tabSpec = args.getString(ARG_TAB_SPEC);

    try {
        JSONObject jsonTab = new JSONObject(tabSpec);

        final String tabName = jsonTab.optString(JsonSpec.TAB_NAME, JsonSpec.DEFAULT_TAB_NAME);
        if (!TextUtils.isEmpty(tabName)) {
            TextView tv = (TextView) rootView.findViewById(R.id.text_view_name);
            tv.setText(tabName);
        }

        tabLayout = (LinearLayout) rootView;

        JSONArray jsonSections = jsonTab.getJSONArray(JsonSpec.SECTIONS_KEY);
        for (int i = 0; i < jsonSections.length(); i++) {
            JSONObject jsonSection = jsonSections.getJSONObject(i);

            LinearLayout sectionLayout = new LinearLayout(context);
            sectionLayout.setOrientation(LinearLayout.VERTICAL);
            tabLayout.addView(sectionLayout);

            // If a section is named, label it.
            final String sectionName = jsonSection.optString(JsonSpec.SECTION_NAME,
                    JsonSpec.DEFAULT_SECTION_NAME);
            if (!TextUtils.isEmpty(sectionName)) {
                TextView textView = new TextView(context);
                textView.setText(sectionName);
                sectionLayout.addView(textView);
            }

            int numColumns = jsonSection.optInt(JsonSpec.SECTION_COLUMNS, JsonSpec.DEFAULT_SECTION_COLUMNS);

            List<View> buttonViews = new LinkedList<View>();

            JSONArray buttons = jsonSection.getJSONArray(JsonSpec.BUTTONS_KEY);
            for (int k = 0; k < buttons.length(); k++) {
                JSONObject jsonButton = buttons.getJSONObject(k);

                ScoreButton buttonView = new ScoreButton(context);
                buttonView.setButtonSpec(jsonButton);
                buttonView.setOnClickListener(mainActivity.getScoreClickListener());

                // Add the button to the section.
                buttonViews.add(buttonView);
            }

            GridView gridView = new GridView(context);
            gridView.setNumColumns(numColumns);
            gridView.setAdapter(new ViewAdapter(context, buttonViews));
            sectionLayout.addView(gridView);
        }
    } catch (JSONException e) {
        Log.th(TAG, e, "onCreateView: failed to parse JSON");
    }

    updateUi();

    return rootView;
}

From source file:ca.appvelopers.mcgillmobile.ui.ScheduleActivity.java

/**
 * Renders the landscape view//from   www  .j  ava 2  s  . c om
 */
private void renderLandscapeView() {
    //Make sure that the necessary views are present in the layout
    Assert.assertNotNull(timetableContainer);
    Assert.assertNotNull(scheduleContainer);

    //Leave space at the top for the day names
    View dayView = View.inflate(this, R.layout.fragment_day_name, null);
    //Black line to separate the timetable from the schedule
    View dayViewLine = dayView.findViewById(R.id.day_line);
    dayViewLine.setVisibility(View.VISIBLE);

    //Add the day view to the top of the timetable
    timetableContainer.addView(dayView);

    //Find the index of the given date
    int currentDayIndex = date.getDayOfWeek().getValue();

    //Go through the 7 days of the week
    for (int i = 1; i < 8; i++) {
        DayOfWeek day = DayOfWeek.of(i);

        //Set up the day name
        dayView = View.inflate(this, R.layout.fragment_day_name, null);
        TextView dayViewTitle = (TextView) dayView.findViewById(R.id.day_name);
        dayViewTitle.setText(DayUtils.getString(this, day));
        scheduleContainer.addView(dayView);

        //Set up the schedule container for that one day
        LinearLayout scheduleContainer = new LinearLayout(this);
        scheduleContainer.setOrientation(LinearLayout.VERTICAL);
        scheduleContainer.setLayoutParams(new LinearLayout.LayoutParams(
                getResources().getDimensionPixelSize(R.dimen.cell_landscape_width),
                ViewGroup.LayoutParams.WRAP_CONTENT));

        //Fill the schedule for the current day
        fillSchedule(this.timetableContainer, scheduleContainer, date.plusDays(i - currentDayIndex), false);

        //Add the current day to the schedule container
        this.scheduleContainer.addView(scheduleContainer);

        //Line
        View line = new View(this);
        line.setBackgroundColor(Color.BLACK);
        line.setLayoutParams(
                new ViewGroup.LayoutParams(getResources().getDimensionPixelSize(R.dimen.schedule_line),
                        ViewGroup.LayoutParams.MATCH_PARENT));
        this.scheduleContainer.addView(line);
    }
}

From source file:com.happysanta.vkspy.Fragments.MainFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    context = getActivity();//from  w  ww . j  av  a  2 s.  c  o m

    if (savedInstanceState != null && UberFunktion.loading) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setMessage(context.getString(R.string.durov_function_activating_message));
        UberFunktion.putNewDialogWindow(dialog);
        dialog.show();
    }

    View rootView = inflater.inflate(R.layout.fragment_main, null);

    View happySanta = inflater.inflate(R.layout.main_santa, null);

    TextView happySantaText = (TextView) happySanta.findViewById(R.id.happySantaText);
    happySantaText.setText(Html.fromHtml(context.getString(R.string.app_description)));
    TextView happySantaLink = (TextView) happySanta.findViewById(R.id.happySantaLink);
    happySantaLink.setText(Html.fromHtml("vk.com/<b>happysanta</b>"));
    happySantaLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://vk.com/happysanta"));
            startActivity(browserIntent);
        }
    });
    happySanta.setOnClickListener(new View.OnClickListener() {
        int i = 1;

        @Override
        public void onClick(View v) {
            if (i < 10)
                i++;
            else {
                i = 0;
                File F = Logs.getFile();
                Uri U = Uri.fromFile(F);
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_STREAM, U);
                startActivity(Intent.createChooser(i, "What should we do with logs?"));
            }
        }
    });

    SharedPreferences longpollPreferences = context.getSharedPreferences("longpoll",
            Context.MODE_MULTI_PROCESS);
    boolean longpollStatus = longpollPreferences.getBoolean("status", true);

    /*Bitmap tile = BitmapFactory.decodeResource(context.getResources(), R.drawable.underline);
    BitmapDrawable tiledBitmapDrawable = new BitmapDrawable(context.getResources(), tile);
    tiledBitmapDrawable.setTileModeX(Shader.TileMode.REPEAT);
    //tiledBitmapDrawable.setTileModeY(Shader.TileMode.REPEAT);
            
    santaGroundView.setBackgroundDrawable(tiledBitmapDrawable);
            
    BitmapDrawable bitmap = new BitmapDrawable(BitmapFactory.decodeResource(
        getResources(), R.drawable.underline2));
    bitmap.setTileModeX(Shader.TileMode.REPEAT);
    */
    LinearLayout layout = (LinearLayout) happySanta.findViewById(R.id.line);
    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int width = display.getWidth(); // deprecated

    for (int i = 0; width % (341 * i + 1) < width; i++) {
        layout.addView(new ImageView(context) {
            {
                setImageResource(R.drawable.underline2);
                setLayoutParams(new ViewGroup.LayoutParams(341, Helper.convertToDp(4)));
                setScaleType(ScaleType.CENTER_CROP);
            }
        });
    }

    ListView preferencesView = (ListView) rootView.findViewById(R.id.preference);
    preferencesView.addHeaderView(happySanta, null, false);
    ArrayList<PreferenceItem> preferences = new ArrayList<PreferenceItem>();
    /*
    preferences.add(new PreferenceItem(getUberfunction(), getUberfunctionDescription()) {
    @Override
    public void onClick() {
            
        if(UberFunktion.loading) {
            ProgressDialog dialog = new ProgressDialog(context);
            dialog.setMessage(context.getString(R.string.durov_function_activating_message));
            UberFunktion.putNewDialogWindow(dialog);
            dialog.show();
            return;
        }
            
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final AlertDialog selector;
        View durov = getActivity().getLayoutInflater().inflate(R.layout.durov, null);
        SharedPreferences durovPreferences = context.getSharedPreferences("durov", Context.MODE_MULTI_PROCESS);
        boolean updateOnly = durovPreferences.getBoolean("loaded", false);
        if(updateOnly)
            ((TextView)durov.findViewById(R.id.description)).setText(R.string.durov_function_activated);
            
            
        if(Memory.users.getById(1)!=null && !updateOnly) {
            builder.setTitle(R.string.durov_joke_title);
            ((TextView)durov.findViewById(R.id.description)).setText(R.string.durov_joke_message);
            ( durov.findViewById(R.id.cat)).setVisibility(View.VISIBLE);
            
            builder.setNegativeButton(R.string.durov_joke_button, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
            
                    BugSenseHandler.sendEvent("? ?  ");
                }
            });
            BugSenseHandler.sendEvent("DUROV FRIEND CATCHED!!1");
        }else{
            builder.setTitle(R.string.durov_start_title);
            
            ( durov.findViewById(R.id.photo)).setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage("http://cs9591.vk.me/v9591001/70/VPSmUR954fQ.jpg",(ImageView) durov.findViewById(R.id.photo));
            builder.
                    setPositiveButton(updateOnly ? R.string.durov_start_update : R.string.durov_start_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
            
                            BugSenseHandler.sendEvent("  ");
                            ProgressDialog uberfunctionDialog = ProgressDialog.show(getActivity(),
                                    context.getString(R.string.durov_function_activating_title),
                                    context.getString(R.string.durov_function_activating_message),
                                    true,
                                    false);
                            UberFunktion.initialize(uberfunctionDialog);
            
                        }
                    });
            builder.setNegativeButton(R.string.durov_start_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
            
                    try {
                        Intent browserIntent = new Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse("https://vk.com/id1")
                        );
                        startActivity(browserIntent);
            
                    }catch(Exception exp){
                        AlertDialog.Builder errorShower = new AlertDialog.Builder(getActivity());
                        if (exp instanceof ActivityNotFoundException) {
                            errorShower.setTitle(R.string.error);
                            errorShower.setMessage(R.string.no_browser);
            
                        } else {
                            errorShower.setTitle(R.string.error);
                            errorShower.setMessage(R.string.unknown_error);
                        }
                        errorShower.show();
                    }
                    BugSenseHandler.sendEvent("? ?  ");
                }
            });
        }
            
        builder.setView(durov);
        selector = builder.create();
        selector.show();
    }
    });
    */

    preferences.add(new ToggleablePreferenceItem(getEnableSpy(), null, longpollStatus) {

        @Override
        public void onToggle(Boolean isChecked) {
            longpollToggle(isChecked);
        }
    });

    preferences.add(new PreferenceItem(getAdvancedSettings()) {
        @Override
        public void onClick() {
            startActivity(new Intent(context, SettingsActivity.class));
        }
    });

    preferences.add(new PreferenceItem(getAbout()) {
        @Override
        public void onClick() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            final AlertDialog aboutDialog;
            builder.setTitle(R.string.app_about).setCancelable(true)
                    .setPositiveButton(R.string.app_about_button, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            View aboutView = getActivity().getLayoutInflater().inflate(R.layout.about, null);

            TextView aboutDescription = (TextView) aboutView.findViewById(R.id.description);
            aboutDescription.setText(Html.fromHtml(getResources().getString(R.string.app_about_description)));
            aboutDescription.setMovementMethod(LinkMovementMethod.getInstance());

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

                    Intent browserIntent = new Intent(context, InfoActivity.class);
                    startActivity(browserIntent);
                }
            });

            builder.setView(aboutView);
            aboutDialog = builder.create();
            aboutDialog.setCanceledOnTouchOutside(true);
            aboutDialog.show();
        }
    });
    preferencesView.setAdapter(new PreferenceAdapter(context, preferences));

    return rootView;

}

From source file:com.cyrilmottier.android.cbrreader.fragment.AboutFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_about, container, false);

    LinearLayout libsLayout = (LinearLayout) view.findViewById(R.id.about_libraries);

    for (int i = 0; i < mDescriptions.length; i++) {
        View cardView = inflater.inflate(R.layout.card_deps, libsLayout, false);

        ((TextView) cardView.findViewById(R.id.libraryName)).setText(mDescriptions[i].name);
        ((TextView) cardView.findViewById(R.id.libraryCreator)).setText(mDescriptions[i].owner);
        ((TextView) cardView.findViewById(R.id.libraryDescription)).setText(mDescriptions[i].description);
        ((TextView) cardView.findViewById(R.id.libraryLicense)).setText(mDescriptions[i].license);

        cardView.setTag(mDescriptions[i].link);
        cardView.setOnClickListener(this);
        libsLayout.addView(cardView);
    }/*from w  w  w . ja  v a2  s .  c  om*/

    return view;
}

From source file:com.airflo.FlightDetailFragment.java

/**
 * Method to build and add the View. It will consider preferences for
 * certain items, textsizes, and handle empty fields.
 *///from  ww w.  java  2s. co  m
public void addViews() {
    table.setColumnShrinkable(1, true);

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(OnlyContext.getContext());
    float detSize = Float.valueOf(sharedPrefs.getString("detailtextsize", "20"));
    boolean hideEmpty = sharedPrefs.getBoolean("detailListPrefEmpty", true);
    for (Identi identi : FlightData.identis.getIdentis()) {
        String prefKey = "detailListPref" + identi.getKey();
        if (sharedPrefs.getBoolean(prefKey, true)) {
            if (hideEmpty) {
                if (mItem.getFromKey(identi.getKey()) == null)
                    continue;
                if (mItem.getFromKey(identi.getKey()).equals(""))
                    continue;
            }
            if (identi.getKey().equals("tag")) {
                if (mItem.getFromKey(identi.getKey()).length() > 0) {
                    LinearLayout lnn = (LinearLayout) rootView.findViewById(R.id.LinearAdditionLayout);
                    String[] tags = mItem.getFromKey(identi.getKey()).split(";");
                    for (String tag : tags) {
                        if (tag.equals("off-field"))
                            tag = "off_field";
                        int resID = getResources().getIdentifier(tag, "drawable", "com.airflo");
                        ImageView img = new ImageView(getActivity());
                        img.setImageResource(resID);
                        img.setPadding(8, 14, 8, 0);
                        lnn.addView(img);
                    }
                }

            } else {
                TableRow row = new TableRow(getActivity());

                header = new TextView(getActivity());
                header.setSingleLine();
                header.setTextSize(detSize);
                header.setText(identi.getStringRep());
                header.setPadding(6, 4, 10, 4);
                row.addView(header);

                cell = new TextView(getActivity());
                cell.setSingleLine(false);
                cell.setTextSize(detSize);
                cell.setText(mItem.getFromKey(identi.getKey()));
                cell.setPadding(6, 4, 6, 4);
                row.addView(cell);

                table.addView(row);
            }

        }
    }
}

From source file:com.ashoksm.pinfinder.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);/*from   w w w. j  ava  2  s  . com*/

    // add to fix crashes in 2.3.x devices due to google play services
    try {
        Class.forName("android.os.AsyncTask");
    } catch (ClassNotFoundException e) {
    }

    // Create the interstitial.
    interstitial = new InterstitialAd(this);
    interstitial.setAdUnitId(getString(R.string.admob_id));

    // load ad
    final LinearLayout adParent = (LinearLayout) this.findViewById(R.id.ad);
    final AdView ad = new AdView(this);
    ad.setAdUnitId(getString(R.string.admob_id));
    ad.setAdSize(AdSize.SMART_BANNER);

    final AdListener listener = new AdListener() {
        @Override
        public void onAdLoaded() {
            adParent.setVisibility(View.VISIBLE);
            super.onAdLoaded();
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            adParent.setVisibility(View.GONE);
            super.onAdFailedToLoad(errorCode);
        }
    };

    ad.setAdListener(listener);

    adParent.addView(ad);
    AdRequest adRequest = new AdRequest.Builder().build();
    ad.loadAd(adRequest);
    // Begin loading your interstitial.
    interstitial.loadAd(adRequest);

    if (savedInstanceState == null) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
        transaction.replace(R.id.pinfinder_content_fragment, fragment);
        transaction.commit();
    }
}

From source file:com.nextgis.mobile.map.LocalTMSLayer.java

protected static void showPropertiesDialog(final MapBase map, final boolean bCreate, String layerName, int type,
        final Uri uri, final LocalTMSLayer layer) {
    final LinearLayout linearLayout = new LinearLayout(map.getContext());
    final EditText input = new EditText(map.getContext());
    input.setText(layerName);//www .  ja va 2  s  .  c o m

    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(map.getContext(),
            android.R.layout.simple_spinner_item);
    final Spinner spinner = new Spinner(map.getContext());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    adapter.add(map.getContext().getString(R.string.tmstype_qtiles));
    adapter.add(map.getContext().getString(R.string.tmstype_osm));
    adapter.add(map.getContext().getString(R.string.tmstype_normal));
    adapter.add(map.getContext().getString(R.string.tmstype_ngw));

    if (type == TMSTYPE_OSM) {
        spinner.setSelection(1);
    } else {
        spinner.setSelection(2);
    }

    final TextView stLayerName = new TextView(map.getContext());
    stLayerName.setText(map.getContext().getString(R.string.layer_name) + ":");

    final TextView stLayerType = new TextView(map.getContext());
    stLayerType.setText(map.getContext().getString(R.string.layer_type) + ":");

    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.addView(stLayerName);
    linearLayout.addView(input);
    linearLayout.addView(stLayerType);
    linearLayout.addView(spinner);

    new AlertDialog.Builder(map.getContext())
            .setTitle(bCreate ? R.string.input_layer_properties : R.string.change_layer_properties)
            //                                    .setMessage(message)
            .setView(linearLayout).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    int tmsType = 0;
                    switch (spinner.getSelectedItemPosition()) {
                    case 0:
                    case 1:
                        tmsType = TMSTYPE_OSM;
                        break;
                    case 2:
                    case 3:
                        tmsType = TMSTYPE_NORMAL;
                        break;
                    }

                    if (bCreate) {
                        create(map, input.getText().toString(), tmsType, uri);
                    } else {
                        layer.setName(input.getText().toString());
                        layer.setTMSType(tmsType);
                        map.onLayerChanged(layer);
                    }
                }
            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                    Toast.makeText(map.getContext(), R.string.error_cancel_by_user, Toast.LENGTH_SHORT).show();
                }
            }).show();
}

From source file:com.ibm.mil.readyapps.physio.fragments.LandingFragment.java

private void setupMetricsTabs(View view) {
    LinearLayout metricsTabsArea = (LinearLayout) view.findViewById(R.id.metrics_tabs_area);

    heartRateTab = new HeartRateMetricsTab(getActivity(), null);
    heartRateTab.setOnClickListener(new View.OnClickListener() {
        @Override/* ww  w.  j a  v  a 2  s  .co  m*/
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.HEART_RATE);
        }
    });
    metricsTabsArea.addView(heartRateTab);

    if (DataManager.getCurrentPatient() == null) {
        return;
    }

    stepsTab = new StepsMetricsTab(getActivity(), null);
    stepsTab.setStepsGoal(DataManager.getCurrentPatient().getStepGoal());
    stepsTab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.STEPS);
        }
    });
    metricsTabsArea.addView(stepsTab);

    weightTab = new WeightMetricsTab(getActivity(), null);
    weightTab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDetailedMetricsScreen(HealthDataRetriever.DataType.WEIGHT);
        }
    });
    metricsTabsArea.addView(weightTab);

    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    cal.add(Calendar.WEEK_OF_YEAR, -1);
    Date startDate = cal.getTime();

    HealthDataRetriever.Builder builder = new HealthDataRetriever.Builder().startDate(startDate).endDate(now)
            .timeUnit(TimeUnit.DAYS).timeInterval(1);

    HealthDataRetriever stepsRetriever = builder.dataType(HealthDataRetriever.DataType.STEPS)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        stepsTab.setSteps(Utils.sum(data));
                    }
                }
            }).build();
    stepsRetriever.retrieve(mClient);

    HealthDataRetriever weightRetriever = builder.dataType(HealthDataRetriever.DataType.WEIGHT)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        int lastWeight = data.get(data.size() - 1);
                        int firstWeight = data.get(0);
                        int netWeight = lastWeight - firstWeight;
                        weightTab.setWeight(lastWeight);
                        weightTab.setNetWeight(netWeight);
                    }
                }
            }).build();
    weightRetriever.retrieve(mClient);

    HealthDataRetriever heartRateRetriever = builder.dataType(HealthDataRetriever.DataType.HEART_RATE)
            .handler(new HealthDataRetriever.Handler() {
                @Override
                public void handle(final List<Integer> data) {
                    if (data != null) {
                        heartRateTab.setBeatsPerMin(Utils.average(data));
                        heartRateTab.setMinMaxBpm(Utils.min(data), Utils.max(data));
                    }
                }
            }).build();
    heartRateRetriever.retrieve(mClient);

    RelativeLayout metricsSwipeArea = (RelativeLayout) view.findViewById(R.id.metrics_swipe_area);

    metricsSwipeArea.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
        @Override
        public void onSwipeLeft() {
            if (!metricsIsOpen) {
                animateMetricsIn(false);
                metricsIsOpen = true;
            }
        }

        @Override
        public void onSwipeRight() {
            if (metricsIsOpen) {
                animateMetricsOut(false);
                metricsIsOpen = false;
            }
        }
    });

    animateMetricsOut(true);
}