Example usage for android.widget LinearLayout findViewById

List of usage examples for android.widget LinearLayout findViewById

Introduction

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

Prototype

@Nullable
public final <T extends View> T findViewById(@IdRes int id) 

Source Link

Document

Finds the first descendant view with the given ID, the view itself if the ID matches #getId() , or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.

Usage

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactDetailFragment.java

/**
 * Builds a phone number LinearLayout based on phone number info from the Contacts Provider.
 * Each phone number gets its own LinearLayout object; for example, if the contact
 * has three phone numbers, then 3 LinearLayouts are generated.
 *
 * @param addressType From/*from w  w  w . jav a2 s. com*/
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided phone details.
 */
private LinearLayout buildPhoneLayout(String phoneNumber, int phoneType) {

    // Inflates the phone number layout
    final LinearLayout phoneLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_phone_item, mPhoneLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_header);
    final TextView phoneTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_item);
    final ImageButton dialNumberButton = (ImageButton) phoneLayout.findViewById(R.id.button_call_number);

    // If there's no phone number for the contact, shows the empty view and message, and hides the
    // header and button.
    if (phoneNumber == null && phoneType == 0) {
        headerTextView.setText("");
        dialNumberButton.setVisibility(View.GONE);
        phoneTextView.setText(R.string.no_address);
    } else {
        headerTextView.setText("Phone Number");
        phoneTextView.setText(phoneNumber);

        // add PhoneStateListener
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager) getActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        // Defines an onClickListener object for the call number button
        dialNumberButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                Intent dialIntent = null;
                if (!phoneTextView.equals("")) {
                    Uri number = Uri.parse("tel:" + phoneTextView.getText());
                    //                  Log.v(ParserApplication.getDebugTag(), "Calling the number: "+number.toString());
                    dialIntent = new Intent(Intent.ACTION_CALL, number);
                    startActivity(dialIntent);
                }
                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(dialIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(dialIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return phoneLayout;
}

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

private void setupItem(LinearLayout item, int itemType, final String key, final String value) {
    switch (itemType) {
    case ITEM_EDIT: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        EditText etValue = (EditText) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);// w  ww .j  a  va 2  s.  c  o  m
        if (!TextUtils.isEmpty(value))
            etValue.setText(value);
        break;
    }
    case ITEM_CHOOSE: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        if (!TextUtils.isEmpty(value))
            tvValue.setText(value);
        break;
    }
    case ITEM_UPLOAD: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        final TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        tvValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadingTextView = tvValue;
                AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
                final String[] items = getResources().getStringArray(R.array.apply_detail_upload);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0: {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                            break;
                        }
                        case 1: {
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File outDir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!outDir.exists()) {
                                    outDir.mkdirs();
                                }
                                File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                photoPath = outFile.getAbsolutePath();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                            } else {
                                CommonUtil.toastShort(ApplyDetailActivity.this,
                                        getString(R.string.toast_no_sdcard));
                            }
                            break;
                        }
                        }
                    }
                });
                builder.show();

            }
        });
        break;
    }
    case ITEM_VIEW: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        ImageButton ibView = (ImageButton) item.findViewById(R.id.apply_detail_view);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        ibView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class);
                i.putExtra("url", value);
                i.putExtra("justviewer", true);
                startActivity(i);
            }
        });
    }
    }
}

From source file:com.github.antoniodisanto92.swipeselector.SwipeAdapter.java

/**
 * Override methods / listeners/*from ww  w. j  a va 2 s  .com*/
 */
@Override
public Object instantiateItem(ViewGroup container, int position) {
    SwipeItem slideItem = mItems.get(position);
    LinearLayout layout = null;

    switch (slideItem.iconGravity) {
    case CENTER:
    case DEFAULT:
        layout = (LinearLayout) View.inflate(mContext, R.layout.swipeselector_content_item, null);
        break;
    case LEFT:
        layout = (LinearLayout) View.inflate(mContext, R.layout.swipeselector_content_left_item, null);
        break;
    case RIGHT:
        layout = (LinearLayout) View.inflate(mContext, R.layout.swipeselector_content_right_item, null);
        break;
    }

    // GET VIEW
    ImageView icon = (ImageView) layout.findViewById(R.id.swipeselector_content_icon);
    TextView title = (TextView) layout.findViewById(R.id.swipeselector_content_title);
    TextView description = (TextView) layout.findViewById(R.id.swipeselector_content_description);

    // SET VIEW
    title.setText(slideItem.title);

    if (slideItem.description == null) {
        description.setVisibility(View.GONE);
    } else {
        description.setVisibility(View.VISIBLE);
        description.setText(slideItem.description);
    }

    if (slideItem.icon == null) {
        icon.setVisibility(View.GONE);
    } else {
        icon.setImageDrawable(slideItem.icon);
        icon.setVisibility(View.VISIBLE);
    }

    // We shouldn't get here if the typeface didn't exist.
    // But just in case, because we're paranoid.
    if (mCustomTypeFace != null) {
        title.setTypeface(mCustomTypeFace);
        description.setTypeface(mCustomTypeFace);
    }

    if (mTitleTextAppearance != -1) {
        setTextAppearanceCompat(title, mTitleTextAppearance);
    }

    if (mDescriptionTextAppearance != -1) {
        setTextAppearanceCompat(description, mDescriptionTextAppearance);
    }

    switch (slideItem.titleGravity) {
    case DEFAULT:
    case CENTER:
        title.setGravity(Gravity.CENTER);
        break;
    case LEFT:
        title.setGravity(Gravity.START);
        break;
    case RIGHT:
        title.setGravity(Gravity.END);
        break;
    }

    switch (slideItem.descriptionGravity) {
    case DEFAULT:
        if (mDescriptionGravity != -1) {
            description.setGravity(mDescriptionGravity);
        } else {
            description.setGravity(Gravity.CENTER);
        }
        break;
    case CENTER:
        description.setGravity(Gravity.CENTER);
        break;
    case LEFT:
        description.setGravity(Gravity.START);
        break;
    case RIGHT:
        description.setGravity(Gravity.END);
        break;
    }

    layout.setPadding(mContentLeftPadding, mSweetSixteen, mContentRightPadding, mSweetSixteen);

    container.addView(layout);
    return layout;
}

From source file:com.gh4a.IssueActivity.java

private void fillData() {
    new LoadCommentsTask(this).execute();

    Typeface boldCondensed = getApplicationContext().boldCondensed;

    ListView lvComments = (ListView) findViewById(R.id.list_view);
    // set details inside listview header
    LayoutInflater infalter = getLayoutInflater();
    LinearLayout mHeader = (LinearLayout) infalter.inflate(R.layout.issue_header, lvComments, false);
    mHeader.setClickable(false);/*from ww  w. ja  v a 2 s.  c  o  m*/

    lvComments.addHeaderView(mHeader, null, false);

    RelativeLayout rlComment = (RelativeLayout) findViewById(R.id.rl_comment);
    if (!isAuthorized()) {
        rlComment.setVisibility(View.GONE);
    }

    TextView tvCommentTitle = (TextView) mHeader.findViewById(R.id.comment_title);
    mCommentAdapter = new CommentAdapter(IssueActivity.this, new ArrayList<Comment>(), mIssue.getNumber(),
            mIssue.getState(), mRepoOwner, mRepoName);
    lvComments.setAdapter(mCommentAdapter);

    ImageView ivGravatar = (ImageView) mHeader.findViewById(R.id.iv_gravatar);
    aq.id(R.id.iv_gravatar).image(GravatarUtils.getGravatarUrl(mIssue.getUser().getGravatarId()), true, false,
            0, 0, aq.getCachedImage(R.drawable.default_avatar), AQuery.FADE_IN);

    ivGravatar.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            getApplicationContext().openUserInfoActivity(IssueActivity.this, mIssue.getUser().getLogin(), null);
        }
    });

    TextView tvExtra = (TextView) mHeader.findViewById(R.id.tv_extra);
    TextView tvState = (TextView) mHeader.findViewById(R.id.tv_state);
    TextView tvTitle = (TextView) mHeader.findViewById(R.id.tv_title);
    TextView tvDescTitle = (TextView) mHeader.findViewById(R.id.desc_title);
    tvDescTitle.setTypeface(getApplicationContext().boldCondensed);
    tvDescTitle.setTextColor(Color.parseColor("#0099cc"));

    tvCommentTitle.setTypeface(getApplicationContext().boldCondensed);
    tvCommentTitle.setTextColor(Color.parseColor("#0099cc"));
    tvCommentTitle
            .setText(getResources().getString(R.string.issue_comments) + " (" + mIssue.getComments() + ")");

    TextView tvDesc = (TextView) mHeader.findViewById(R.id.tv_desc);
    tvDesc.setMovementMethod(LinkMovementMethod.getInstance());

    TextView tvMilestone = (TextView) mHeader.findViewById(R.id.tv_milestone);

    ImageView ivComment = (ImageView) findViewById(R.id.iv_comment);
    if (Gh4Application.THEME == R.style.DefaultTheme) {
        ivComment.setImageResource(R.drawable.social_send_now_dark);
    }
    ivComment.setBackgroundResource(R.drawable.abs__list_selector_holo_dark);
    ivComment.setPadding(5, 2, 5, 2);
    ivComment.setOnClickListener(this);

    tvExtra.setText(mIssue.getUser().getLogin() + "\n" + pt.format(mIssue.getCreatedAt()));
    tvState.setTextColor(Color.WHITE);
    if ("closed".equals(mIssue.getState())) {
        tvState.setBackgroundResource(R.drawable.default_red_box);
        tvState.setText("C\nL\nO\nS\nE\nD");
    } else {
        tvState.setBackgroundResource(R.drawable.default_green_box);
        tvState.setText("O\nP\nE\nN");
    }
    tvTitle.setText(mIssue.getTitle());
    tvTitle.setTypeface(boldCondensed);

    boolean showInfoBox = false;
    if (mIssue.getAssignee() != null) {
        showInfoBox = true;
        TextView tvAssignee = (TextView) mHeader.findViewById(R.id.tv_assignee);
        tvAssignee.setText(mIssue.getAssignee().getLogin() + " is assigned");
        tvAssignee.setVisibility(View.VISIBLE);
        tvAssignee.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getApplicationContext().openUserInfoActivity(IssueActivity.this,
                        mIssue.getAssignee().getLogin(), null);
            }
        });

        ImageView ivAssignee = (ImageView) mHeader.findViewById(R.id.iv_assignee);

        aq.id(R.id.iv_assignee).image(GravatarUtils.getGravatarUrl(mIssue.getAssignee().getGravatarId()), true,
                false, 0, 0, aq.getCachedImage(R.drawable.default_avatar), AQuery.FADE_IN);

        ivAssignee.setVisibility(View.VISIBLE);
        ivAssignee.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getApplicationContext().openUserInfoActivity(IssueActivity.this,
                        mIssue.getAssignee().getLogin(), null);
            }
        });
    }

    if (mIssue.getMilestone() != null) {
        showInfoBox = true;
        tvMilestone.setText(
                getResources().getString(R.string.issue_milestone) + ": " + mIssue.getMilestone().getTitle());
    } else {
        tvMilestone.setVisibility(View.GONE);
    }

    String body = mIssue.getBodyHtml();
    if (!StringUtils.isBlank(body)) {
        HttpImageGetter imageGetter = new HttpImageGetter(this);
        body = HtmlUtils.format(body).toString();
        imageGetter.bind(tvDesc, body, mIssue.getNumber());
    }

    LinearLayout llLabels = (LinearLayout) findViewById(R.id.ll_labels);
    List<Label> labels = mIssue.getLabels();

    if (labels != null && !labels.isEmpty()) {
        showInfoBox = true;
        for (Label label : labels) {
            TextView tvLabel = new TextView(this);
            tvLabel.setSingleLine(true);
            tvLabel.setText(label.getName());
            tvLabel.setTextAppearance(this, R.style.default_text_small);
            tvLabel.setBackgroundColor(Color.parseColor("#" + label.getColor()));
            tvLabel.setPadding(5, 2, 5, 2);
            int r = Color.red(Color.parseColor("#" + label.getColor()));
            int g = Color.green(Color.parseColor("#" + label.getColor()));
            int b = Color.blue(Color.parseColor("#" + label.getColor()));
            if (r + g + b < 383) {
                tvLabel.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
            } else {
                tvLabel.setTextColor(getResources().getColor(android.R.color.primary_text_light));
            }
            llLabels.addView(tvLabel);

            View v = new View(this);
            v.setLayoutParams(new LayoutParams(5, LayoutParams.WRAP_CONTENT));
            llLabels.addView(v);
        }
    } else {
        llLabels.setVisibility(View.GONE);
    }

    TextView tvPull = (TextView) mHeader.findViewById(R.id.tv_pull);
    if (mIssue.getPullRequest() != null && mIssue.getPullRequest().getDiffUrl() != null) {
        showInfoBox = true;
        tvPull.setVisibility(View.VISIBLE);
        tvPull.setOnClickListener(this);
    }

    if (!showInfoBox) {
        RelativeLayout rl = (RelativeLayout) mHeader.findViewById(R.id.info_box);
        rl.setVisibility(View.GONE);
    }
}

From source file:org.ounl.lifelonglearninghub.learntracker.gis.ou.swipe.TimeLineActivity.java

/**
 * Removes record both from sqlite and backend
 * //w w  w.  j a  v  a 2  s.c  om
 * @param v
 */
public void onClickDeleteActivity(View v) {

    LinearLayout llCheckItemRow = (LinearLayout) v.getParent();
    LinearLayout llCheckItemWrapper = (LinearLayout) llCheckItemRow.getParent();
    int iNumItemsHistory = 0;
    int iTag = 0;
    int iClicked = 0;

    try {

        llHistory = (LinearLayout) llCheckItemWrapper.getParent();

        llListFragment = (LinearLayout) llHistory.getParent();

        iNumItemsHistory = ((llHistory.getChildCount() - 1) / 2) - 1;
        iTag = new Integer(llCheckItemWrapper.getTag().toString());
        iClicked = (iTag - iNumItemsHistory) * (-1);
        iToRemove = (iClicked + 1) * 2;

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

    TextView myText = (TextView) llCheckItemRow.findViewById(R.id.textViewTimeStamp);
    lCheckInToDelete = (Long) myText.getTag();
    String sCheckIn = (String) myText.getText();
    TextView tvDur = (TextView) llCheckItemRow.findViewById(R.id.textViewDuration);
    sIdSbuject = (String) tvDur.getTag();

    new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Remove activity?")
            .setMessage("Are you sure to remove activity started at " + sCheckIn + " ?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //Toast.makeText(getApplicationContext(), "About to delete activity "+sCheckIn+" ... ", Toast.LENGTH_SHORT).show();      
                    Log.d(CLASSNAME, "About to delte activity   mills[" + lCheckInToDelete + "]");

                    // Delete this transactional
                    // Issue 16
                    // https://code.google.com/p/lifelong-learning-hub/issues/detail?id=16      
                    deleteActivityBackend(lCheckInToDelete, Session.getSingleInstance().getUserName());
                    Session.getSingleInstance().getDatabaseHandler().deleteActivity(lCheckInToDelete);

                    DateUtils du = new DateUtils();

                    TextView tvDuration = (TextView) llListFragment.findViewById(R.id.tvDuration);
                    tvDuration.setText(du.duration(
                            Session.getSingleInstance().getDatabaseHandler().getAccumulatedTime(sIdSbuject)));

                    llHistory.getChildAt(iToRemove).setVisibility(View.GONE);

                    //Stop the activity
                    //TimeLineActivity.this.finish();    
                }

            }).setNegativeButton("No", null).show();

}

From source file:anastasoft.rallyvision.activity.MenuPrincipal.java

public void makeConnectOn() {
    LinearLayout mConnectLayout = (LinearLayout) findViewById(R.id.ConnecLayout);

    mConnectLayout.removeAllViews();/*from  w  ww  . j  a va2s  . co m*/

    // Create new LayoutInflater - this has to be done this way, as you can't directly inflate an XML without creating an inflater object first
    LayoutInflater inflater = getLayoutInflater();
    mConnectLayout.addView(inflater.inflate(R.layout.connect_button_green, null));
    mConnectLayout.findViewById(R.id.executar).setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            stopCom(v);
            return true;
        }
    });

}

From source file:anastasoft.rallyvision.activity.MenuPrincipal.java

public void makeConnectOff() {
    LinearLayout mConnectLayout = (LinearLayout) findViewById(R.id.ConnecLayout);
    mConnectLayout.removeAllViews();/*from   w w w  .ja v  a2 s  .  co m*/

    // Create new LayoutInflater - this has to be done this way, as you can't directly inflate an XML without creating an inflater object first
    LayoutInflater inflater = getLayoutInflater();
    mConnectLayout.addView(inflater.inflate(R.layout.connect_button_green_escuro, null));
    mConnectLayout.findViewById(R.id.executar).setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            startProcedure(v);

            return true;
        }
    });

}

From source file:im.vector.activity.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (CommonActivityUtils.shouldRestartApp()) {
        Log.e(LOG_TAG, "Restart the application.");
        CommonActivityUtils.restartApp(this);
    }/*  ww  w . jav  a 2s  .  co  m*/

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_settings);

    mMediasCache = Matrix.getInstance(this).getMediasCache();

    // add any known session
    LinearLayout globalLayout = (LinearLayout) findViewById(R.id.settings_layout);
    TextView profileHeader = (TextView) findViewById(R.id.settings_profile_information_header);
    int pos = globalLayout.indexOfChild(profileHeader);

    for (MXSession session : Matrix.getMXSessions(this)) {
        final MXSession fSession = session;

        LinearLayout profileLayout = (LinearLayout) getLayoutInflater()
                .inflate(R.layout.account_section_settings, null);
        mLinearLayoutBySession.put(session, profileLayout);

        pos++;
        globalLayout.addView(profileLayout, pos);
        refreshProfileThumbnail(session, profileLayout);

        ImageView avatarView = (ImageView) profileLayout.findViewById(R.id.imageView_avatar);

        avatarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUpdatingSession = fSession;
                Intent fileIntent = new Intent(Intent.ACTION_PICK);
                fileIntent.setType("image/*");
                startActivityForResult(fileIntent, REQUEST_IMAGE);
            }
        });

        MyUser myUser = session.getMyUser();

        TextView matrixIdTextView = (TextView) profileLayout.findViewById(R.id.textView_matrix_id);
        matrixIdTextView.setText(myUser.userId);

        final Button saveButton = (Button) profileLayout.findViewById(R.id.button_save);

        EditText displayNameEditText = (EditText) profileLayout.findViewById(R.id.editText_displayName);
        displayNameEditText.setText(myUser.displayname);
        displayNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateSaveButton(saveButton);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveChanges(fSession);
            }
        });
    }

    // Config information

    String versionName = "";

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        versionName = pInfo.versionName;
    } catch (Exception e) {

    }

    TextView consoleVersionTextView = (TextView) findViewById(R.id.textView_matrixConsoleVersion);
    consoleVersionTextView.setText(getString(R.string.settings_config_console_version, versionName));

    TextView sdkVersionTextView = (TextView) findViewById(R.id.textView_matrixSDKVersion);
    sdkVersionTextView.setText(getString(R.string.settings_config_sdk_version, versionName));

    TextView buildNumberTextView = (TextView) findViewById(R.id.textView_matrixBuildNumber);
    buildNumberTextView.setText(getString(R.string.settings_config_build_number, ""));

    TextView userIdTextView = (TextView) findViewById(R.id.textView_configUsers);
    String config = "";

    int sessionIndex = 1;

    Collection<MXSession> sessions = Matrix.getMXSessions(this);

    for (MXSession session : sessions) {

        if (sessions.size() > 1) {
            config += "\nAccount " + sessionIndex + " : \n";
            sessionIndex++;
        }

        config += String.format(getString(R.string.settings_config_home_server),
                session.getCredentials().homeServer);
        config += "\n";

        config += String.format(getString(R.string.settings_config_user_id), session.getMyUser().userId);

        if (sessions.size() > 1) {
            config += "\n";
        }
    }

    userIdTextView.setText(config);

    // room settings
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    listenBoxUpdate(preferences, R.id.checkbox_useGcm,
            getString(R.string.settings_key_use_google_cloud_messaging), true);
    listenBoxUpdate(preferences, R.id.checkbox_displayAllEvents,
            getString(R.string.settings_key_display_all_events), false);
    listenBoxUpdate(preferences, R.id.checkbox_hideUnsupportedEvenst,
            getString(R.string.settings_key_hide_unsupported_events), true);
    listenBoxUpdate(preferences, R.id.checkbox_sortByLastSeen,
            getString(R.string.settings_key_sort_by_last_seen), true);
    listenBoxUpdate(preferences, R.id.checkbox_displayLeftMembers,
            getString(R.string.settings_key_display_left_members), false);
    listenBoxUpdate(preferences, R.id.checkbox_displayPublicRooms,
            getString(R.string.settings_key_display_public_rooms_recents), true);

    final Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache);

    clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")");

    clearCacheButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Matrix.getInstance(SettingsActivity.this).reloadSessions(SettingsActivity.this);
        }
    });

    final Button notificationsRuleButton = (Button) findViewById(R.id.button_notifications_rule);

    notificationsRuleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchNotificationsActivity();
        }
    });

    final GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this)
            .getSharedGcmRegistrationManager();

    refreshGCMEntries();

    final EditText pusherUrlEditText = (EditText) findViewById(R.id.editText_gcm_pusher_url);
    pusherUrlEditText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            gcmRegistrationManager.setPusherUrl(pusherUrlEditText.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    final EditText pusherProfileEditText = (EditText) findViewById(R.id.editText_gcm_pusher_profile_tag);
    pusherProfileEditText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            gcmRegistrationManager.setPusherFileTag(pusherProfileEditText.getText().toString());
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    managePedingGCMregistration();
}

From source file:com.farmerbb.taskbar.fragment.AdvancedFragment.java

@SuppressLint("SetTextI18n")
@Override//from   ww  w  . j a va 2s. c  o m
public boolean onPreferenceClick(final Preference p) {
    final SharedPreferences pref = U.getSharedPreferences(getActivity());

    switch (p.getKey()) {
    case "clear_pinned_apps":
        Intent clearIntent = null;

        switch (pref.getString("theme", "light")) {
        case "light":
            clearIntent = new Intent(getActivity(), ClearDataActivity.class);
            break;
        case "dark":
            clearIntent = new Intent(getActivity(), ClearDataActivityDark.class);
            break;
        }

        startActivity(clearIntent);
        break;
    case "launcher":
        if (U.canDrawOverlays(getActivity())) {
            ComponentName component = new ComponentName(getActivity(), HomeActivity.class);
            getActivity().getPackageManager().setComponentEnabledSetting(component,
                    ((CheckBoxPreference) p).isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                            : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        } else {
            U.showPermissionDialog(getActivity());
            ((CheckBoxPreference) p).setChecked(false);
        }

        if (!((CheckBoxPreference) p).isChecked())
            LocalBroadcastManager.getInstance(getActivity())
                    .sendBroadcast(new Intent("com.farmerbb.taskbar.KILL_HOME_ACTIVITY"));
        break;
    case "keyboard_shortcut":
        ComponentName component = new ComponentName(getActivity(), KeyboardShortcutActivity.class);
        getActivity().getPackageManager()
                .setComponentEnabledSetting(component,
                        ((CheckBoxPreference) p).isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);
        break;
    case "dashboard_grid_size":
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LinearLayout dialogLayout = (LinearLayout) View.inflate(getActivity(), R.layout.dashboard_size_dialog,
                null);

        boolean isPortrait = getActivity().getApplicationContext().getResources()
                .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
        boolean isLandscape = getActivity().getApplicationContext().getResources()
                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;

        int editTextId = -1;
        int editText2Id = -1;

        if (isPortrait) {
            editTextId = R.id.fragmentEditText2;
            editText2Id = R.id.fragmentEditText1;
        }

        if (isLandscape) {
            editTextId = R.id.fragmentEditText1;
            editText2Id = R.id.fragmentEditText2;
        }

        final EditText editText = (EditText) dialogLayout.findViewById(editTextId);
        final EditText editText2 = (EditText) dialogLayout.findViewById(editText2Id);

        builder.setView(dialogLayout).setTitle(R.string.dashboard_grid_size)
                .setPositiveButton(R.string.action_ok, (dialog, id) -> {
                    boolean successfullyUpdated = false;

                    String widthString = editText.getText().toString();
                    String heightString = editText2.getText().toString();

                    if (widthString.length() > 0 && heightString.length() > 0) {
                        int width = Integer.parseInt(widthString);
                        int height = Integer.parseInt(heightString);

                        if (width > 0 && height > 0) {
                            SharedPreferences.Editor editor = pref.edit();
                            editor.putInt("dashboard_width", width);
                            editor.putInt("dashboard_height", height);
                            editor.apply();

                            updateDashboardGridSize(true);
                            successfullyUpdated = true;
                        }
                    }

                    if (!successfullyUpdated)
                        U.showToast(getActivity(), R.string.invalid_grid_size);
                }).setNegativeButton(R.string.action_cancel, null);

        editText.setText(Integer.toString(pref.getInt("dashboard_width",
                getActivity().getApplicationContext().getResources().getInteger(R.integer.dashboard_width))));
        editText2.setText(Integer.toString(pref.getInt("dashboard_height",
                getActivity().getApplicationContext().getResources().getInteger(R.integer.dashboard_height))));

        AlertDialog dialog = builder.create();
        dialog.show();

        new Handler().post(() -> {
            InputMethodManager imm = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText2, InputMethodManager.SHOW_IMPLICIT);
        });

        break;
    case "navigation_bar_buttons":
        Intent intent = null;

        switch (pref.getString("theme", "light")) {
        case "light":
            intent = new Intent(getActivity(), NavigationBarButtonsActivity.class);
            break;
        case "dark":
            intent = new Intent(getActivity(), NavigationBarButtonsActivityDark.class);
            break;
        }

        startActivity(intent);
        break;
    }

    return true;
}

From source file:org.matrix.console.activity.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (CommonActivityUtils.shouldRestartApp()) {
        Log.e(LOG_TAG, "Restart the application.");
        CommonActivityUtils.restartApp(this);
    }// w  w  w .  j av a  2s .  c  o m

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_settings);

    mMediasCache = Matrix.getInstance(this).getMediasCache();

    // add any known session
    LinearLayout globalLayout = (LinearLayout) findViewById(R.id.settings_layout);
    TextView profileHeader = (TextView) findViewById(R.id.settings_profile_information_header);
    int pos = globalLayout.indexOfChild(profileHeader);

    for (MXSession session : Matrix.getMXSessions(this)) {
        final MXSession fSession = session;

        LinearLayout profileLayout = (LinearLayout) getLayoutInflater()
                .inflate(R.layout.account_section_settings, null);
        mLinearLayoutByMatrixId.put(session.getCredentials().userId, profileLayout);

        pos++;
        globalLayout.addView(profileLayout, pos);
        refreshProfileThumbnail(session, profileLayout);

        ImageView avatarView = (ImageView) profileLayout.findViewById(R.id.imageView_avatar);

        avatarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUpdatingSessionId = fSession.getCredentials().userId;
                Intent fileIntent = new Intent(Intent.ACTION_PICK);
                fileIntent.setType("image/*");
                startActivityForResult(fileIntent, REQUEST_IMAGE);
            }
        });

        MyUser myUser = session.getMyUser();

        TextView matrixIdTextView = (TextView) profileLayout.findViewById(R.id.textView_matrix_id);
        matrixIdTextView.setText(myUser.userId);

        final Button saveButton = (Button) profileLayout.findViewById(R.id.button_save);

        EditText displayNameEditText = (EditText) profileLayout.findViewById(R.id.editText_displayName);
        displayNameEditText.setText(myUser.displayname);
        displayNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateSaveButton(saveButton);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveChanges(fSession);
            }
        });
    }

    // Config information

    String versionName = "";

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        versionName = pInfo.versionName;
    } catch (Exception e) {

    }

    TextView consoleVersionTextView = (TextView) findViewById(R.id.textView_matrixConsoleVersion);
    consoleVersionTextView.setText(getString(R.string.settings_config_console_version, versionName));

    TextView sdkVersionTextView = (TextView) findViewById(R.id.textView_matrixSDKVersion);
    sdkVersionTextView.setText(getString(R.string.settings_config_sdk_version, versionName));

    TextView buildNumberTextView = (TextView) findViewById(R.id.textView_matrixBuildNumber);
    buildNumberTextView.setText(getString(R.string.settings_config_build_number, ""));

    TextView userIdTextView = (TextView) findViewById(R.id.textView_configUsers);
    String config = "";

    int sessionIndex = 1;

    Collection<MXSession> sessions = Matrix.getMXSessions(this);

    for (MXSession session : sessions) {

        if (sessions.size() > 1) {
            config += "\nAccount " + sessionIndex + " : \n";
            sessionIndex++;
        }

        config += String.format(getString(R.string.settings_config_home_server),
                session.getHomeserverConfig().getHomeserverUri().toString());
        config += "\n";

        config += String.format(getString(R.string.settings_config_user_id), session.getMyUser().userId);

        if (sessions.size() > 1) {
            config += "\n";
        }
    }

    userIdTextView.setText(config);

    // room settings
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    listenBoxUpdate(preferences, R.id.checkbox_useGcm,
            getString(R.string.settings_key_use_google_cloud_messaging), true);
    listenBoxUpdate(preferences, R.id.checkbox_displayAllEvents,
            getString(R.string.settings_key_display_all_events), false);
    listenBoxUpdate(preferences, R.id.checkbox_hideUnsupportedEvenst,
            getString(R.string.settings_key_hide_unsupported_events), true);
    listenBoxUpdate(preferences, R.id.checkbox_sortByLastSeen,
            getString(R.string.settings_key_sort_by_last_seen), true);
    listenBoxUpdate(preferences, R.id.checkbox_displayLeftMembers,
            getString(R.string.settings_key_display_left_members), false);
    listenBoxUpdate(preferences, R.id.checkbox_displayPublicRooms,
            getString(R.string.settings_key_display_public_rooms_recents), true);
    listenBoxUpdate(preferences, R.id.checkbox_rageshake, getString(R.string.settings_key_use_rage_shake),
            true);

    final Button clearCacheButton = (Button) findViewById(R.id.button_clear_cache);

    clearCacheButton.setText(getString(R.string.clear_cache) + " (" + computeApplicationCacheSize() + ")");

    clearCacheButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Matrix.getInstance(SettingsActivity.this).reloadSessions(SettingsActivity.this);
        }
    });

    final Button notificationsRuleButton = (Button) findViewById(R.id.button_notifications_rule);

    notificationsRuleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchNotificationsActivity();
        }
    });

    final GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(this)
            .getSharedGcmRegistrationManager();

    refreshGCMEntries();

    managePedingGCMregistration();
}