Example usage for android.widget TextView setGravity

List of usage examples for android.widget TextView setGravity

Introduction

In this page you can find the example usage for android.widget TextView setGravity.

Prototype

public void setGravity(int gravity) 

Source Link

Document

Sets the horizontal alignment of the text and the vertical gravity that will be used when there is extra space in the TextView beyond what is required for the text itself.

Usage

From source file:com.sssemil.sonyirremote.ir.ir.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        setContentView(R.layout.settings_ir);
        main = false;// ww  w  .j  a  v a 2  s .  c  o  m

        final GetAwItems getAwItems1 = new GetAwItems(ir.this);
        String ret = getAwItems1.execute().get();

        spinner6 = ((Spinner) findViewById(R.id.spinner6));
        spinner6.setSelection(0);

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                ar);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner6.setAdapter(dataAdapter);

        prepItemBrandArray();

        return true;
    } else if (id == R.id.action_about) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.about));
        PackageInfo pInfo = null;
        String version = "?";
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        version = pInfo.versionName;
        builder.setMessage(getResources().getString(R.string.license1) + " v" + version + "\n"
                + getResources().getString(R.string.license2) + "\n"
                + getResources().getString(R.string.license3) + "\n"
                + getResources().getString(R.string.license4));
        builder.setPositiveButton("OK", null);
        AlertDialog dialog = builder.show();

        TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
        messageView.setGravity(Gravity.CENTER);
        return true;
    } else if (id == R.id.action_exit) {
        stopIR();
        System.exit(0);
        return true;
    } else if (id == R.id.action_update) {
        update();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.sdspikes.fireworks.FireworksActivity.java

private TextView makeNewCardTextView(int width, GameState.Card card) {
    width = Math.min(width, MAX_CARD_WIDTH);
    width = Math.max(width, MIN_CARD_WIDTH);
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
    TextView textView = new TextView(this);
    textView.setLayoutParams(params);//w w  w.j av a2 s  . c  om
    textView.setGravity(Gravity.CENTER);
    textView.setText(String.valueOf(card.rank));
    textView.setBackgroundResource(HandFragment.cardColorToBGColor.get(card.color));
    textView.setTextColor(getResources().getColor(HandFragment.cardColorToTextColor(card.color)));
    return textView;
}

From source file:com.justone.android.main.MainActivity.java

@SuppressWarnings("deprecation")
@Override/*from w w w.  j  a v a  2  s  .c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    currentContext = this;
    //listviewview
    this.viewMap = new HashMap<String, ListViewAdapter>();
    //
    this.asynImageLoader = JustOne.getAsynImageLoader();
    this.dataOp = JustOne.getDataOp();

    //
    this.res = getResources(); // Resource object to get Drawables  

    // 
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
            .detectNetwork().penaltyLog().build());
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
            .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

    justOne = (JustOne) getApplication();
    justOne.pushActivity(this);
    // view
    LayoutInflater inflater = LayoutInflater.from(this);
    //details_page_setitem = inflater.inflate(R.layout.one_details_page_setitem, null);
    main_item = inflater.inflate(R.layout.activity_main, null);
    bind_item = inflater.inflate(R.layout.one_details_page_binditem, null);
    about_one = inflater.inflate(R.layout.about_one, null);
    //microblog = inflater.inflate(R.layout.one_details_page_microblog, null);

    feedback = inflater.inflate(R.layout.feedback, null);

    setContentView(main_item);

    initData();

    // view
    mListView = (ListView) findViewById(R.id.tab2);
    //ArrayList<ArrayList<String>> list_data = loadData("list",data);
    listAdapter = new ListViewAdapter(this, mList, mGist, R.id.scrollview, R.layout.list_item);

    mListView.setAdapter(listAdapter);

    /*
    mListView1 = (ListView) findViewById(R.id.tab1);
            
    //ArrayList<ArrayList<String>> collect_data = loadData("collect",data);
    collectAdapter = new ListViewAdapter(this,mList,
    mGist, R.id.collectScrollview,
    R.layout.collect_item);
            
    mListView1.setAdapter(collectAdapter);
    */
    homeListView = (ListView) findViewById(R.id.homeTab);
    homeAdapter = new ListViewAdapter(this, mList, mGist, R.id.homeScrollView, R.layout.home_item);

    homeListView.setAdapter(homeAdapter);

    qaListView = (ListView) findViewById(R.id.QAtab);

    //ArrayList<ArrayList<String>> QA_data = loadData("QA",data);
    QAAdapter = new ListViewAdapter(this, mList, mGist, R.id.qaScrollView, R.layout.qa_item);

    qaListView.setAdapter(QAAdapter);

    //detailView = (ListView) findViewById(R.id.tab3);

    //ArrayList<ArrayList<String>> detail_data = loadData("detail",data);
    //detailAdapter = new ListViewAdapter(this,
    //      mList, mGist,
    //      R.id.detailScrollView, R.layout.detail_item);

    //detailView.setAdapter(detailAdapter);

    /*//loading list view 
    loadingView = (ListView) findViewById(R.id.loading_view);
            
    //ArrayList<ArrayList<String>> detail_data = loadData("detail",data);
    loadingAdapter = new ListViewAdapter(this,
    mList, mGist,
    R.id.loadingScrollView, R.layout.one_welcome_ad);
            
    loadingView.setAdapter(loadingAdapter);
            
    */

    tabs = (TabHost) findViewById(R.id.tabhost);
    tabWidget = (TabWidget) findViewById(android.R.id.tabs);
    int width = 100;
    int height = 100;
    tabs.setup();
    tabs.addTab(tabs.newTabSpec("home tab").setIndicator("", this.res.getDrawable(R.drawable.home_tab_selector))
            .setContent(R.id.homeTab));
    tabs.addTab(tabs.newTabSpec("list tab").setIndicator("", this.res.getDrawable(R.drawable.one_tab_selector))
            .setContent(R.id.tab2));
    tabs.addTab(tabs.newTabSpec("QA Tab").setIndicator("", this.res.getDrawable(R.drawable.qa_tab_selector))
            .setContent(R.id.QAtab));

    /*
    tabs.addTab(tabs.newTabSpec("second tab").setIndicator("", null)
    .setContent(R.id.tab1));*/
    //tabs.addTab(tabs.newTabSpec("second tab").setIndicator("",this.res.getDrawable(R.drawable.more_tab_selector))
    //      .setContent(R.id.tab3));

    tabs.setCurrentTab(0);
    for (int i = 0; i < tabWidget.getChildCount(); i++) {
        /**
         * fill_parent
         */
        tabWidget.getChildAt(i).getLayoutParams().height = height;
        tabWidget.getChildAt(i).getLayoutParams().width = width;

        /**
         * tab
         */
        final TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
        tv.setTextColor(this.getResources().getColorStateList(android.R.color.white));
        tv.setTextSize(15);
        tv.setGravity(Gravity.TOP);
    }
    mActivityName = getString(R.string.activity_c_label);
    mStatusTracker.setStatus(mActivityName, getString(R.string.on_create));
    Utils.printStatus(mStatusView, mStatusAllView);
    detector = new GestureDetector(this);
    viewMap.put("home", this.homeAdapter);

    //
    View returnBackToIndex = main_item.findViewById(R.id.returnBackToIndex_layout);
    returnBackToIndex.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            MainActivity.this.finish();
            // TODO Auto-generated method stub

        }
    });

    userFirstTips();

}

From source file:com.b44t.ui.ActionBar.BottomSheet.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Window window = getWindow();//from  ww w .  j  av a  2  s  .  com
    window.setWindowAnimations(R.style.DialogNoAnimation);
    setContentView(container, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

    if (containerView == null) {
        containerView = new FrameLayout(getContext()) {
            @Override
            public boolean hasOverlappingRendering() {
                return false;
            }
        };
        containerView.setBackgroundDrawable(shadowDrawable);
        containerView.setPadding(backgroundPaddingLeft,
                (applyTopPadding ? AndroidUtilities.dp(8) : 0) + backgroundPaddingTop, backgroundPaddingLeft,
                (applyBottomPadding ? AndroidUtilities.dp(8) : 0));
    }
    if (Build.VERSION.SDK_INT >= 21) {
        containerView.setFitsSystemWindows(true);
    }
    containerView.setVisibility(View.INVISIBLE);
    container.addView(containerView, 0,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM));

    if (customView != null) {
        if (customView.getParent() != null) {
            ViewGroup viewGroup = (ViewGroup) customView.getParent();
            viewGroup.removeView(customView);
        }
        containerView.addView(customView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
    } else {
        int topOffset = 0;
        if (title != null) {
            TextView titleView = new TextView(getContext());
            titleView.setLines(1);
            titleView.setSingleLine(true);
            titleView.setText(title);
            titleView.setTextColor(0xff757575);
            titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
            titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
            titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8));
            titleView.setGravity(Gravity.CENTER_VERTICAL);
            containerView.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48));
            titleView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            topOffset += 48;
        }
        if (items != null) {
            FrameLayout rowLayout = null;
            int lastRowLayoutNum = 0;
            for (int a = 0; a < items.length; a++) {
                BottomSheetCell cell = new BottomSheetCell(getContext(), 0);
                cell.setTextAndIcon(items[a], itemIcons != null ? itemIcons[a] : 0);
                containerView.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48,
                        Gravity.LEFT | Gravity.TOP, 0, topOffset, 0, 0));
                topOffset += 48;
                cell.setTag(a);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismissWithButtonClick((Integer) v.getTag());
                    }
                });
                itemViews.add(cell);
            }
        }
    }

    WindowManager.LayoutParams params = window.getAttributes();
    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.dimAmount = 0;
    params.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    if (!focusable) {
        params.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
    }
    params.height = ViewGroup.LayoutParams.MATCH_PARENT;
    window.setAttributes(params);
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void setAudio(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        @Override//from  w w w  .java  2 s. c  o  m
        public void run() {
            setOnClickView(tag, getString(R.string.gallery_tap_to_play), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!settings.useInternalAudioPlayer()) {
                        openExternal();
                    } else {
                        recycleTag(tag, false);
                        final TextView durationView = new TextView(GalleryActivity.this);
                        durationView.setGravity(Gravity.CENTER);
                        tag.layout.setVisibility(View.VISIBLE);
                        tag.layout.addView(durationView);
                        tag.audioPlayer = new MediaPlayer();
                        tag.audioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(final MediaPlayer mp) {
                                mp.setLooping(true);

                                durationView.setText(
                                        getSpannedText("00:00 / " + formatMediaPlayerTime(mp.getDuration())));

                                tag.timer = new Timer();
                                tag.timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    durationView.setText(getSpannedText(
                                                            formatMediaPlayerTime(mp.getCurrentPosition())
                                                                    + " / "
                                                                    + formatMediaPlayerTime(mp.getDuration())));
                                                } catch (Exception e) {
                                                    Logger.e(TAG, e);
                                                    tag.timer.cancel();
                                                }
                                            }
                                        });
                                    }
                                }, 1000, 1000);

                                mp.start();
                            }
                        });
                        tag.audioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                Logger.e(TAG, "(Audio) Error code: " + what);
                                if (tag.timer != null)
                                    tag.timer.cancel();
                                showError(tag, getString(R.string.gallery_error_play));
                                return true;
                            }
                        });
                        try {
                            tag.audioPlayer.setDataSource(file.getAbsolutePath());
                            tag.audioPlayer.prepareAsync();
                        } catch (Exception e) {
                            Logger.e(TAG, "audio player error", e);
                            if (tag.timer != null)
                                tag.timer.cancel();
                            showError(tag, getString(R.string.gallery_error_play));
                        }
                    }
                }
            });
        }
    });
}

From source file:com.cybrosys.scientific.EventListener.java

@SuppressWarnings("deprecation")
public void showHistory() {
    shPref = ScientificActivity.ctx.getSharedPreferences("myHistpref", 0);
    int inSize = shPref.getInt("HistIndex", 0);
    System.out.println("" + inSize);
    String[] str = new String[inSize];
    for (int inI = 0; inI < inSize; inI++) {
        str[inI] = shPref.getString("hist" + inI, "");
        System.out.println(str[inI]);
    }//from ww w  . j  av  a2  s.c  o  m
    LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    vwLayout = inflater.inflate(R.layout.pop_history,
            (ViewGroup) ((Activity) ctx).findViewById(R.id.popup_element));

    popmW1 = new PopupWindow(vwLayout, PalmCalcActivity.inDispwidth, PalmCalcActivity.inDispheight, true);
    popmW1.setBackgroundDrawable(new BitmapDrawable());
    popmW1.setOutsideTouchable(true);
    popmW1.showAtLocation(vwLayout, Gravity.CENTER, 0, 0);
    tblltTable = (TableLayout) vwLayout.findViewById(R.id.tablelay);
    ImageButton btnCancel = (ImageButton) vwLayout.findViewById(R.id.butcancelmain);
    btnCancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            popmW1.dismiss();

        }
    });
    txtvHistory = new TextView[inSize];
    btnHistory = new Button[inSize];
    tblrRowL = new TableRow[inSize];
    TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT, 1f);
    TableRow.LayoutParams textParams = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT, .1f);
    int inJ = 0, inL = inSize - 1;
    for (int inI = 0; inI < inSize; inI++) {
        if (!str[inI].equalsIgnoreCase("")) {
            btnHistory[inJ] = new Button(ctx);
            txtvHistory[inJ] = new TextView(ctx);
            txtvHistory[inJ].setText("" + (inJ + 1));
            txtvHistory[inJ].setGravity(Gravity.CENTER);
            txtvHistory[inJ].setTextColor(ScientificActivity.ctx.getResources().getColor(R.color.HistColor));
            txtvHistory[inJ].setLayoutParams(textParams);
            btnHistory[inJ].setText(str[inL]);
            btnHistory[inJ].setTextColor(Color.WHITE);
            btnHistory[inJ].setGravity(Gravity.LEFT);
            btnHistory[inJ].setLayoutParams(buttonParams);
            btnHistory[inJ].setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.button_effect));
            tblrRowL[inJ] = new TableRow(ctx);
            tblrRowL[inJ].addView(txtvHistory[inJ]);
            tblrRowL[inJ].addView(btnHistory[inJ]);
            tblltTable.addView(tblrRowL[inJ]);
            final int inK = inJ;
            btnHistory[inK].setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // etxt.setText(btns[inK].getText().toString());
                    mHandler.insert(btnHistory[inK].getText().toString());
                    popmW1.dismiss();
                }
            });

            inJ++;
            inL--;
        }

    }
    if (inSize == 0) {
        TextView txtvHistory = new TextView(ctx);
        txtvHistory.setLayoutParams(textParams);
        txtvHistory.setGravity(Gravity.CENTER);
        txtvHistory.setTextColor(Color.WHITE);
        txtvHistory.setText("History Empty");
        TableRow tblrRowL = new TableRow(ctx);
        tblrRowL.addView(txtvHistory);
        tblltTable.addView(tblrRowL);
    }
}

From source file:com.sdspikes.fireworks.FireworksActivity.java

private TextView makeAttributeTextView(final int rank, final GameState.CardColor color) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    int oneButtonWidth = mDiscardWidthR2 / 10;
    int marginWidth = oneButtonWidth / 10;
    params.setMargins(marginWidth, 5, marginWidth, 5);
    params.width = oneButtonWidth - marginWidth * 2;
    params.height = params.width;/*  www.j av a2s .com*/

    TextView textView = new TextView(this);
    textView.setLayoutParams(params);
    textView.setText(String.valueOf(rank));
    if (rank == -1)
        textView.setText(" ");
    textView.setGravity(Gravity.CENTER);
    textView.setBackgroundResource(HandFragment.cardColorToBGColor.get(color));
    textView.setTextColor(getResources().getColor(HandFragment.cardColorToTextColor(color)));
    textView.setVisibility(View.VISIBLE);

    textView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d(TAG,
                    "clicked on an attribute button: " + GameState.Card.cardColorToString(color) + " " + rank);
            List<GameState.Card> hand = mTurnData.state.hands.get(mRecipientPlayer).hand;
            List<Integer> locations = new ArrayList<Integer>();
            String info = "";
            if (rank == -1) {
                info = GameState.Card.cardColorToString(color);
                for (int i = 0; i < hand.size(); i++) {
                    if (hand.get(i).color == color)
                        locations.add(i);
                }
            } else {
                info = HandFragment.rankToString(rank);
                for (int i = 0; i < hand.size(); i++) {
                    if (hand.get(i).rank == rank)
                        locations.add(i);
                }
            }
            if (locations.size() == 0) {
                Toast.makeText(FireworksActivity.this,
                        mIdToName.get(mRecipientPlayer) + " does not have any " + info, Toast.LENGTH_SHORT);
            } else {
                int[] positions = new int[locations.size()];
                for (int i = 0; i < positions.length; i++) {
                    // Make the positions 1-indexed
                    positions[i] = locations.get(i) + 1;
                }
                LogItem item = new InfoLogItem(mMyId, mRecipientPlayer, info, positions);

                actionLog.add(item.toString());
                mTurnData.state.hintsRemaining--;
                mTurnData.state.currentPlayerId = mTurnData.state.hands
                        .get(mTurnData.state.currentPlayerId).nextPlayerId;
                togglePlayOptionsVisible(PlayOptions.turnMessage);
                broadcastGameInfo(item.getJSONObject());
                updateAllPlayers(mTurnData.getJSONObject());
                mRecipientPlayer = null;
            }
        }
    });
    return textView;
}

From source file:com.adarshahd.indianrailinfo.donate.PNRStat.java

private void showOfflinePNRStatus(String trainDetails, ArrayList<String> passnDetails) {
    LinearLayout ll = new LinearLayout(mActivity);

    TextView textViewTrnDtls = new TextView(mActivity);
    TextView textViewPsnDtls = new TextView(mActivity);
    TextView tvTrainDetails = new TextView(mActivity);
    TextView[] tvPassnDetails = new TextView[passnDetails.size()];

    textViewTrnDtls.setText("Train Details: " + mPNRNumber);
    textViewTrnDtls.setFocusable(true);//from   ww  w.ja v  a  2  s .c  o m
    textViewPsnDtls.setText("Passenger Details");
    tvTrainDetails.setText(trainDetails);
    textViewTrnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    textViewPsnDtls.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Large);
    tvTrainDetails.setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Small);
    textViewTrnDtls.setPadding(10, 10, 10, 10);
    textViewPsnDtls.setPadding(10, 10, 10, 10);
    tvTrainDetails.setPadding(10, 10, 10, 10);

    tvTrainDetails.setBackgroundResource(R.drawable.card_background);
    textViewTrnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    textViewPsnDtls.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    ll.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(textViewTrnDtls);

    ll.addView(tvTrainDetails);
    ll.addView(textViewPsnDtls);
    for (int i = 0; i < passnDetails.size(); ++i) {
        tvPassnDetails[i] = new TextView(mActivity);
        tvPassnDetails[i].setText(passnDetails.get(i));
        tvPassnDetails[i].setPadding(10, 10, 10, 10);
        tvPassnDetails[i].setBackgroundResource(R.drawable.card_background);
        tvPassnDetails[i].setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Medium);
        ll.addView(tvPassnDetails[i]);
    }
    mFrameLayout.removeAllViews();
    mFrameLayout.addView(ll);
}

From source file:com.cairoconfessions.MainActivity.java

public void addLocation(View view) {
    TextView newView = new TextView(this);
    AutoCompleteTextView addLoc = ((AutoCompleteTextView) findViewById(R.id.addLocation));
    String newLoc = addLoc.getText().toString();
    ViewGroup locList = ((ViewGroup) findViewById(R.id.locations));
    boolean notFound = true;
    for (int i = 0; i < locList.getChildCount(); i++) {
        if (newLoc.equals(((TextView) locList.getChildAt(i)).getText().toString()))
            notFound = false;//from  w  w w . j a va 2s. com
        break;
    }
    if (Arrays.asList(COUNTRIES).contains(newLoc) && notFound) {
        newView.setText(newLoc);
        newView.setClickable(true);
        newView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                addItem(view);
            }
        });
        float scale = getResources().getDisplayMetrics().density;
        newView.setGravity(17);
        newView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);

        newView.setBackgroundResource(R.drawable.city2);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                (int) (150 * scale));
        lp.setMargins((int) (0 * scale), (int) (0 * scale), (int) (0 * scale), (int) (2 * scale));
        newView.setLayoutParams(lp);
        locList.addView(newView, 0);
        addLoc.setText("");
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(addLoc.getWindowToken(), 0);
        addLoc.setCursorVisible(false);

    } else {
        Toast.makeText(this, "Invalid location", Toast.LENGTH_LONG).show();
    }
}

From source file:com.android.contacts.common.list.ViewPagerTabs.java

private void addTab(CharSequence tabTitle, final int position) {
    View tabView;/*from   w  w  w . ja v  a2 s  . c  om*/
    if (mTabIcons != null && position < mTabIcons.length) {
        View layout = LayoutInflater.from(getContext()).inflate(R.layout.unread_count_tab, null);
        View iconView = layout.findViewById(R.id.icon);
        iconView.setBackgroundResource(mTabIcons[position]);
        iconView.setContentDescription(tabTitle);
        TextView textView = (TextView) layout.findViewById(R.id.count);
        if (mUnreadCounts != null && mUnreadCounts[position] > 0) {
            textView.setText(Integer.toString(mUnreadCounts[position]));
            textView.setVisibility(View.VISIBLE);
            iconView.setContentDescription(
                    getResources().getQuantityString(R.plurals.tab_title_with_unread_items,
                            mUnreadCounts[position], tabTitle.toString(), mUnreadCounts[position]));
        } else {
            textView.setVisibility(View.INVISIBLE);
            iconView.setContentDescription(tabTitle);
        }
        tabView = layout;
    } else {
        final TextView textView = new TextView(getContext());
        textView.setText(tabTitle);
        textView.setBackgroundResource(R.drawable.view_pager_tab_background);

        // Assign various text appearance related attributes to child views.
        if (mTextStyle > 0) {
            textView.setTypeface(textView.getTypeface(), mTextStyle);
        }
        if (mTextSize > 0) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        }
        if (mTextColor != null) {
            textView.setTextColor(mTextColor);
        }
        textView.setAllCaps(mTextAllCaps);
        textView.setGravity(Gravity.CENTER);

        tabView = textView;
    }

    tabView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mPager.setCurrentItem(getRtlPosition(position));
        }
    });

    tabView.setOnLongClickListener(new OnTabLongClickListener(position));

    tabView.setPadding(mSidePadding, 0, mSidePadding, 0);

    mTabStrip.addView(tabView, position,
            new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1));

    // Default to the first child being selected
    if (position == 0) {
        mPrevSelected = 0;
        tabView.setSelected(true);
    }
}