Java Code Examples for android.widget.TextView

The following are top voted examples for showing how to use android.widget.TextView. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: MDP-Group-10   File: MapGenerator.java View source code Vote up 8 votes
private void createArena(GridLayout gv)
{
	Log.i("tag", "at create arena");
       TextView tv;
       int counter =0;
       
       for (int row=0; row<15; row++){
       	for (int col=0; col<20; col++){
       		tv = new TextView(this.context);
       		tv.setBackgroundColor(Color.parseColor("#686868")); //arena colour
       		
       		tv.setId(counter);
       		tv.setText(Integer.toString(tv.getId()));
       		tv.setGravity(Gravity.CENTER);
       		
       		tv.setTextSize(9);
       		tv.setWidth(37);
          		tv.setHeight(37);
          		gv.addView(tv);
          		counter++;
          		
       	}
       }

       
}
 
Example 2
Project: iosched4eclipse   File: BrowseSessionsActivity.java View source code Vote up 7 votes
private void setUpNormalDropdownView(int position, TextView textView) {
    textView.setText(getTitle(position));
    ShapeDrawable colorDrawable = (ShapeDrawable) textView.getCompoundDrawables()[2];
    int color = getColor(position);
    if (color == 0) {
        if (colorDrawable != null) {
            textView.setCompoundDrawables(null, null, null, null);
        }
    } else {
        if (mDotSize == 0) {
            mDotSize = getResources().getDimensionPixelSize(
                    R.dimen.tag_color_dot_size);
        }
        if (colorDrawable == null) {
            colorDrawable = new ShapeDrawable(new OvalShape());
            colorDrawable.setIntrinsicWidth(mDotSize);
            colorDrawable.setIntrinsicHeight(mDotSize);
            colorDrawable.getPaint().setStyle(Paint.Style.FILL);
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, colorDrawable, null);
        }
        colorDrawable.getPaint().setColor(color);
    }

}
 
Example 3
Project: my-ministry-assistant   File: MainActivity.java View source code Vote up 6 votes
private View makeNavDrawerItem(final int itemId, ViewGroup container) {
    boolean selected = getDefaultNavDrawerItem() == itemId;
    int layoutToInflate = 0;
    
    if (itemId == NAVDRAWER_ITEM_SEPARATOR) {
        layoutToInflate = R.layout.navdrawer_separator;
    } else {
        layoutToInflate = R.layout.navdrawer_item;
    }
    
    View view = getLayoutInflater().inflate(layoutToInflate, container, false);

    if (isSeparator(itemId)) {
        // we are done
        UIUtils.setAccessibilityIgnore(view);
        return view;
    }

    ImageView iconView = (ImageView) view.findViewById(R.id.icon);
    TextView titleView = (TextView) view.findViewById(R.id.title);
    int iconId = itemId >= 0 && itemId < NAVDRAWER_ICON_RES_ID.length ? NAVDRAWER_ICON_RES_ID[itemId] : 0;
    int titleId = itemId >= 0 && itemId < NAVDRAWER_TITLE_RES_ID.length ? NAVDRAWER_TITLE_RES_ID[itemId] : 0;
    
    // set icon and text
    iconView.setVisibility(iconId > 0 ? View.VISIBLE : View.GONE);
    if (iconId > 0) {
        iconView.setImageResource(iconId);
    }
    titleView.setText(getString(titleId));

    formatNavDrawerItem(view, itemId, selected);

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNavDrawerItemClicked(itemId);
        }
    });

    return view;
}
 
Example 4
Project: my-ministry-assistant   File: EntryTypeManagerFrag.java View source code Vote up 6 votes
@SuppressLint("InflateParams")
private void showEditTextDialog(final int id, String name, int isActive) {
	View view = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.d_edit_text_with_cb, null);
   	AlertDialog.Builder builder = new Builder(EntryTypeManagerFrag.this.getActivity());
   	final EditText editText = (EditText) view.findViewById(R.id.text1);
   	final CheckBox cb_is_active = (CheckBox) view.findViewById(R.id.cb_is_active);
   	final TextView tv_note = (TextView) view.findViewById(R.id.tv_note);
   	
   	editText.setText(name);
   	cb_is_active.setChecked(isActive != 0 ? true : false);
   	
   	if(id == MinistryDatabase.ID_ROLLOVER) {
   		cb_is_active.setEnabled(false);
   		cb_is_active.setTextColor(getActivity().getApplicationContext().getResources().getColor(R.color.holo_grey_light));
   		tv_note.setVisibility(View.VISIBLE);
   	}
   	
   	builder.setView(view);
   	builder.setTitle(id != MinistryDatabase.CREATE_ID ? R.string.form_rename : R.string.form_name);
	builder.setNegativeButton(R.string.menu_cancel, null); // Do nothing on cancel - this will dismiss the dialog :)
	builder.setPositiveButton(R.string.menu_save, new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			if(values == null)
				values = new ContentValues();
			
			values.put(EntryType.NAME, editText.getText().toString());
			values.put(EntryType.RBC, id != MinistryDatabase.ID_RBC ? MinistryService.INACTIVE : MinistryService.ACTIVE);
			
			if(id != MinistryDatabase.ID_ROLLOVER)
				values.put(EntryType.ACTIVE, (cb_is_active.isChecked()) ? MinistryService.ACTIVE : MinistryService.INACTIVE);
			else
				values.put(EntryType.ACTIVE, MinistryService.INACTIVE);
			
			database.openWritable();
			
			if(id != MinistryDatabase.CREATE_ID)
				database.saveEntryType(id, values);
			else
				database.createEntryType(values);
			
			reloadCursor();
			
			database.close();
		}
	});
	builder.show();
   }
 
Example 5
Project: my-ministry-assistant   File: MainActivity.java View source code Vote up 6 votes
private void formatNavDrawerItem(View view, int itemId, boolean selected) {
    if (isSeparator(itemId)) {
        // not applicable
        return;
    }

    //ImageView iconView = (ImageView) view.findViewById(R.id.icon);
    TextView titleView = (TextView) view.findViewById(R.id.title);

    // configure its appearance according to whether or not it's selected
    titleView.setTextColor(selected ?
            getResources().getColor(R.color.navdrawer_text_color_selected) :
            getResources().getColor(R.color.navdrawer_text_color));
    /*
    iconView.setColorFilter(selected ?
            getResources().getColor(R.color.navdrawer_icon_tint_selected) :
            getResources().getColor(R.color.navdrawer_icon_tint));
            */
    if(selected)
    	setTitle(titleView.getText());
    
}
 
Example 6
Project: Gui2Go   File: HomeActivity.java View source code Vote up 6 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);

    // Init the activity
    recentList = (ListView) findViewById(R.id.recentsList);
    recentList.setOnItemClickListener(new ProjectItemClickListener());
    recentList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    TextView emptyText = new TextView(this);
    emptyText.setText("No Projects!");
    emptyText.setTextSize(24);
    recentList.setEmptyView(emptyText);

    UpdateRecentsList();

    setTitle("");

    // showFirstTimeHelpDialog();
    if (isFirstLaunch()) {
        showFirstTimeHelpDialog();

        // Save the preferences, isFirstLaunch will now be false
        SharedPreferences settings = getSharedPreferences("prefs", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isFirstLaunch", false);
        editor.commit();
    }
}
 
Example 7
Project: flow-android   File: ProfileCoursesAdapter.java View source code Vote up 6 votes
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String termName = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.profile_courses_list_header_item, null);
    }
    TextView first = (TextView) convertView.findViewById(R.id.first);
    first.setTypeface(null, Typeface.BOLD);
    first.setText(termName);

    return convertView;
}
 
Example 8
Project: arduino-android   File: DroidTempLogger.java View source code Vote up 6 votes
protected void showControls() {
	super.showControls();

	mInputLabel = (TextView) findViewById(R.id.inputLabel);
	mInputContainer = (LinearLayout) findViewById(R.id.inputContainer);
	mInputLabel.setOnClickListener(this);

	showTabContents(true);
}
 
Example 9
Project: BioWiki   File: AppLogViewerActivity.java View source code Vote up 6 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logviewer_activity);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);

    mTxtLogViewer = (TextView) findViewById(R.id.text_log);
    mTxtLogViewer.setText(Html.fromHtml(AppLog.toHtml(this)));

    // this is necessary to enable the textView to scroll vertically
    mTxtLogViewer.setMovementMethod(ScrollingMovementMethod.getInstance());
}
 
Example 10
Project: BioWiki   File: MessageBarUtils.java View source code Vote up 6 votes
public static void showMessageBar(final Activity activity,
                                  final String message,
                                  final MessageBarType messageBarType,
                                  final Runnable runnable) {
    if (activity == null)
        return;

    final TextView txtMessageBar = (TextView) activity.findViewById(R.id.text_message_bar);
    if (txtMessageBar == null)
        return;
    if (txtMessageBar.getVisibility() == View.VISIBLE)
        return;

    switch (messageBarType) {
        case INFO:
            txtMessageBar.setBackgroundResource(R.color.reader_message_bar_blue);
            break;
        case ALERT:
            txtMessageBar.setBackgroundResource(R.color.reader_message_bar_orange);
            break;
        default:
            return;
    }

    txtMessageBar.clearAnimation();
    txtMessageBar.setText(message);

    AniUtils.startAnimation(txtMessageBar, R.anim.reader_message_bar_in);
    txtMessageBar.setVisibility(View.VISIBLE);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            hideMessageBar(activity, runnable, false);
        }
    }, DELAY_MILLIS);
}
 
Example 11
Project: Orange-Android-Demos   File: PagerSlidingTabStrip.java View source code Vote up 6 votes
private void addTextTab(final int position, String title) {

		TextView tab = new TextView(getContext());
		tab.setText(title);
		tab.setGravity(Gravity.CENTER);
		tab.setSingleLine();

		addTab(position, tab);
	}
 
Example 12
Project: Android_Blog_Demos   File: IntentServiceActivity.java View source code Vote up 6 votes
public void addTask(View view)
{
    //????
    String path = "/sdcard/imgs/" + (++i) + ".png";
    UploadImgService.startUploadImg(this, path);

    TextView tv = new TextView(this);
    mLyTaskContainer.addView(tv);
    tv.setText(path + " is uploading ...");
    tv.setTag(path);
}
 
Example 13
Project: codereview.chromium   File: LinkifiedTextView.java View source code Vote up 6 votes
@Override
    public boolean onTouchEvent(MotionEvent event) {
        TextView widget = this;
        Object text = widget.getText();
        if (text instanceof Spanned) {
            Spanned buffer = (Spanned) text;
            int action = event.getAction();
            if (action == MotionEvent.ACTION_UP
                    || action == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                x -= widget.getTotalPaddingLeft();
                y -= widget.getTotalPaddingTop();

                x += widget.getScrollX();
                y += widget.getScrollY();

                Layout layout = widget.getLayout();
                int line = layout.getLineForVertical(y);
                int off = layout.getOffsetForHorizontal(line, x);

                ClickableSpan[] link = buffer.getSpans(off, off,
                        ClickableSpan.class);

                if (link.length != 0) {
                    if (action == MotionEvent.ACTION_UP) {
                        link[0].onClick(widget);
                    } else if (action == MotionEvent.ACTION_DOWN) {
                        //TODO: fix selection
//                        Selection.setSelection(buffer,
//                                buffer.getSpanStart(link[0]),
//                                buffer.getSpanEnd(link[0]));
                    }
                    return true;
                }
            }

        }

        return false;
    }
 
Example 14
Project: scope   File: AboutPreference.java View source code Vote up 6 votes
@Override
   protected void onBindDialogView(View view)
   {
// Get version text view

TextView version = (TextView) view.findViewById(R.id.about);

// Get context and package manager

Context context = getContext();
PackageManager manager = context.getPackageManager();

// Get info

PackageInfo info = null;
try
{
    info = manager.getPackageInfo("org.billthefarmer.scope", 0);
}
	
catch (NameNotFoundException e)
{
    e.printStackTrace();
}

// Set version in text view

if (info != null)
{
    String v = (String) version.getText();
    String s = String.format(v, info.versionName);
    version.setText(s);
}
   }
 
Example 15
Project: Orange-Android-Demos   File: PagerSlidingTabStrip.java View source code Vote up 6 votes
private void updateTabStyles() {

		for (int i = 0; i < tabCount; i++) {

			View v = tabsContainer.getChildAt(i);

			v.setBackgroundResource(tabBackgroundResId);

			if (v instanceof TextView) {

				TextView tab = (TextView) v;
				tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
				tab.setTypeface(tabTypeface, tabTypefaceStyle);
				tab.setTextColor(tabTextColor);

				// setAllCaps() is only available from API 14, so the upper case
				// is made manually if we are on a
				// pre-ICS-build
				if (textAllCaps) {
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
						tab.setAllCaps(true);
					} else {
						tab.setText(tab.getText().toString()
								.toUpperCase(locale));
					}
				}
			}
		}

	}
 
Example 16
Project: androiddevice.info   File: DeviceInformationListAdapter.java View source code Vote up 6 votes
@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if(null == view){
            view = mInflater.inflate(R.layout.editable_list_item, parent, false);
        }
        KeyValuePair pair = getItem(position);
        if(null != pair){
            TextView key = ((TextView)view.findViewById(android.R.id.text1));
            key.setText(pair.key);
            key.setTextColor(mWhiteColor);

            final TextView value = ((TextView)view.findViewById(android.R.id.text2));
            final TextView editable  = ((TextView)view.findViewById(R.id.editable));

            if(pair.isEditable){
                value.setVisibility(View.GONE);
                editable.setVisibility(View.VISIBLE);
                if(null != mDeviceName && mDeviceName.length() > 0) {
                    editable.setText(mDeviceName);
                }
            } else {
                value.setVisibility(View.VISIBLE);
                editable.setVisibility(View.GONE);
                value.setText(pair.valueString);
                value.setTextColor(mGreyColor);
                value.setMaxLines(10);
                value.setEllipsize(TextUtils.TruncateAt.END);
            }

            //details.setVisibility(TextView.GONE);

//            ((TextView)view.findViewById(android.R.id.text1)).setOnClickListener(new View.OnClickListener() {
//                private TextView detailsItem = details;
//                @Override
//                public void onClick(View view) {
//                    if(detailsItem.getVisibility() == TextView.VISIBLE) {
//                        detailsItem.setVisibility(TextView.GONE);
//                    } else if(detailsItem.getVisibility() == TextView.GONE) {
//                        detailsItem.setVisibility(TextView.VISIBLE);
//                    }
//                }
//            });
        }
        return view;
    }
 
Example 17
Project: SensorsWebLogger   File: HandleSensors.java View source code Vote up 6 votes
public HandleSensors (Context context, TextView txtView) {
    SensorManager sensorManager = null;

    if (txtView != null) txtView.append("Detecting Sensors\n");

    sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

    List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
    for (Sensor sensor : sensors) {
        if (txtView != null) txtView.append("Sensor: " + sensor.getName() + "\n");
    }

    sensorSingle = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    if (sensorSingle != null) {
        sensorClasses.add(SensorLight.class);
    } else {
        if (txtView != null) txtView.append("No light sensor!\n");
    }

    sensorSingle = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    if (sensorSingle != null) {
        sensorClasses.add(SensorAmbientTemperature.class);
    } else {
        if (txtView != null) txtView.append("No ambient temperature sensor!\n");
    }

    sensorSingle = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    if (sensorSingle != null) {
        sensorClasses.add(SensorPressure.class);
    } else {
        if (txtView != null) txtView.append("No pressure sensor!\n");
    }

    sensorSingle = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    if (sensorSingle != null) {
        sensorClasses.add(SensorRelativeHumidity.class);
    } else {
        if (txtView != null) txtView.append("No relative humidity sensor!\n");
    }

}
 
Example 18
Project: doode-android   File: SidebarAdapter.java View source code Vote up 6 votes
public View getView(int position, View view, ViewGroup parent) {
    SidebarEntry entry = mItens.get(position);

    if (view == null) {
        view = LayoutInflater.from(Doode.getAppContext())
                .inflate(R.layout.sidebar_item, parent, false);
    }
    TextView textView = (TextView) view;
    textView.setText(entry.name);
    Drawable img = Doode.getAppContext().getResources().getDrawable(entry.drawableID);
    textView.setCompoundDrawables(img, null, null, null);
    return view;
}
 
Example 19
Project: BioWiki   File: FollowRow.java View source code Vote up 6 votes
private void updateFollowButton(boolean isFollowing) {
    final TextView followButton = getFollowButton();
    int drawableId = (isFollowing ? R.drawable.note_icon_following : R.drawable.note_icon_follow);
    followButton.setCompoundDrawablesWithIntrinsicBounds(drawableId, 0, 0, 0);
    followButton.setSelected(isFollowing);
    followButton.setText(isFollowing ? R.string.reader_btn_unfollow : R.string.reader_btn_follow);
}
 
Example 20
Project: retroboy   File: PreferenceListAdapter.java View source code Vote up 6 votes
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	if (convertView == null) {
	    LayoutInflater inflater = (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    convertView = inflater.inflate(R.layout.detailed_preference_item, parent, false);
	}
	
    TextView titleView = (TextView)convertView.findViewById(R.id.prefItemTitle);
    TextView valueView = (TextView)convertView.findViewById(R.id.prefItemValue);

    PreferenceItem item = _items.get(position);
    titleView.setText(item._title);
    valueView.setText(item.getValueLabel());
    valueView.setEnabled(item.isEnabled());
    return convertView;
}
 
Example 21
Project: BigPangOrderManager   File: ViewTopItem.java View source code Vote up 6 votes
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
	this.innerView.measure(widthMeasureSpec, heightMeasureSpec);
	ImageView iv1 = (ImageView)this.innerView.findViewById(R.id.top_item_1);
	LayoutParams lp = iv1.getLayoutParams();
	lp.height = iv1.getMeasuredWidth();
	iv1.setLayoutParams(lp);
	
	ImageView iv2 = (ImageView)this.innerView.findViewById(R.id.top_item_2);
	lp = iv2.getLayoutParams();
	lp.height = iv2.getMeasuredWidth();
	iv2.setLayoutParams(lp);
	
	ImageView iv3 = (ImageView)this.innerView.findViewById(R.id.top_item_3);
	lp = iv3.getLayoutParams();
	lp.height = iv3.getMeasuredWidth();
	iv3.setLayoutParams(lp);
	
	TextView tv = (TextView)this.innerView.findViewById(R.id.top_item_others);
	lp = tv.getLayoutParams();
	lp.height = iv3.getMeasuredWidth();
	tv.setLayoutParams(lp);
	
	this.innerView.measure(widthMeasureSpec, heightMeasureSpec);
	
	this.setMeasuredDimension(this.innerView.getMeasuredWidth(), this.innerView.getMeasuredHeight());
}
 
Example 22
Project: android-sholi   File: ItemLazyListAdapter.java View source code Vote up 6 votes
@Override
public void bindView(View view, Context context, Item item) {
    TextView name = (TextView) view.findViewById(R.id.item_name);
    name.setText(item.getName());
    name.setTextSize(getTextSize());
    switch (item.getStatus()) {
        case Checkable.OFF_LIST:
            name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            name.setTextColor(Color.GRAY);
            break;
        case Checkable.UNCHECKED:
            name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            name.setTextColor(Color.GREEN);
            break;
        case Checkable.CHECKED:
            name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            name.setTextColor(Color.WHITE);
            break;
    }
}
 
Example 23
Project: cardslib   File: MayKnowCard.java View source code Vote up 6 votes
@Override
public void setupInnerViewElements(ViewGroup parent, View view) {

    TextView title = (TextView) view.findViewById(R.id.carddemo_mayknow_main_inner_title);
    TextView subtitle = (TextView) view.findViewById(R.id.carddemo_mayknow_main_inner_subtitle);
    TextView add = (TextView) view.findViewById(R.id.carddemo_mayknow_main_inner_button);

    title.setText(getContext().getString(R.string.may_know_card_inner_title));
    subtitle.setText(getContext().getString(R.string.may_know_card_inner_subtitle));
    add.setClickable(true);

    CardViewWrapper cardView = getCardView();
    CardThumbnailView thumb = cardView.getInternalThumbnailLayout();
    if (thumb != null) {
        ViewGroup.LayoutParams lp = thumb.getLayoutParams();
        if (lp instanceof ViewGroup.MarginLayoutParams) {
            ((ViewGroup.MarginLayoutParams) lp).setMargins(25, 0, 0, 5);
        }
    }


}
 
Example 24
Project: ExcusePro   File: DefaultHeaderTransformer.java View source code Vote up 6 votes
@Override
public void onViewCreated(Activity activity, View headerView) {
    // Get ProgressBar and TextView. Also set initial text on TextView
    mHeaderProgressBar = (ProgressBar) headerView.findViewById(R.id.ptr_progress);
    mHeaderTextView = (TextView) headerView.findViewById(R.id.ptr_text);

    // Apply any custom ProgressBar colors
    applyProgressBarColor();

    // Labels to display
    mPullRefreshLabel = activity.getString(R.string.pull_to_refresh_pull_label);
    mRefreshingLabel = activity.getString(R.string.pull_to_refresh_refreshing_label);
    mReleaseLabel = activity.getString(R.string.pull_to_refresh_release_label);

    // Retrieve the Action Bar size from the Activity's theme
    mContentLayout = (ViewGroup) headerView.findViewById(R.id.ptr_content);
    if (mContentLayout != null) {
        mContentLayout.getLayoutParams().height = getActionBarSize(activity);
        mContentLayout.requestLayout();
    }

    // Retrieve the Action Bar background from the Activity's theme (see #93).
    Drawable abBg = getActionBarBackground(activity);
    if (abBg != null) {
        // If we do not have a opaque background we just display a solid solid behind it
        if (abBg.getOpacity() != PixelFormat.OPAQUE) {
            View view = headerView.findViewById(R.id.ptr_text_opaque_bg);
            if (view != null) {
                view.setVisibility(View.VISIBLE);
            }
        }

        mHeaderTextView.setBackgroundDrawable(abBg);
    }

    // Retrieve the Action Bar Title Style from the Action Bar's theme
    Context abContext = headerView.getContext();
    final int titleTextStyle = getActionBarTitleStyle(abContext);
    if (titleTextStyle != 0) {
        mHeaderTextView.setTextAppearance(abContext, titleTextStyle);
    }

    // Call onReset to make sure that the View is consistent
    onReset();
}
 
Example 25
Project: AnSiAn   File: MorseReceiveView.java View source code Vote up 6 votes
@Override
protected void init() {
	LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	inflater.inflate(R.layout.morse_receive_view, this);
	codeText = (TextView) findViewById(R.id.code_text);
	symbolText = (TextView) findViewById(R.id.symbol_text);
	decoder = new Decoder();
	codeText.setGravity(Gravity.RIGHT);
	codeText.setHorizontallyScrolling(true);
	symbolText.setGravity(Gravity.RIGHT);
	symbolText.setHorizontallyScrolling(true);
	MorseCodeEvent event = EventBus.getDefault().getStickyEvent(MorseCodeEvent.class);
	if (event != null) {
		codeBuffer = new StringBuffer(event.getCompleteCodeString());
		codeText.setText(codeBuffer);
		symbolText.setText(new StringBuilder().append(decoder.decode(cutString(codeBuffer))));
	} else {
		codeBuffer = new StringBuffer();
	}

}
 
Example 26
Project: DemoProject   File: TaskListView.java View source code Vote up 6 votes
/** Expands the views for individual list entries, and sets content descriptions for use by the
 *  TaskBackAccessibilityService.
 */
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(R.layout.tasklist_row, parent, false);
    }

    CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.tasklist_finished);
    checkbox.setChecked(mCheckboxes[position]);

    TextView label = (TextView)(convertView.findViewById(R.id.tasklist_label));
    label.setText(mLabels[position]);

    String contentDescription = new StringBuilder()
            .append(mContext.getString(R.string.task_name))
            .append(' ')
            .append(mLabels[position]).toString();
    label.setContentDescription(contentDescription);

    convertView.setTag(position);

    return convertView;
}
 
Example 27
Project: property-db   File: Touch.java View source code Vote up 6 votes
/**
 * Scrolls the specified widget to the specified coordinates, except
 * constrains the X scrolling position to the horizontal regions of
 * the text that will be visible after scrolling to the specified
 * Y position.
 */
public static void scrollTo(TextView widget, Layout layout, int x, int y) {
    final int horizontalPadding = widget.getTotalPaddingLeft() + widget.getTotalPaddingRight();
    final int availableWidth = widget.getWidth() - horizontalPadding;

    final int top = layout.getLineForVertical(y);
    Alignment a = layout.getParagraphAlignment(top);
    boolean ltr = layout.getParagraphDirection(top) > 0;

    int left, right;
    if (widget.getHorizontallyScrolling()) {
        final int verticalPadding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
        final int bottom = layout.getLineForVertical(y + widget.getHeight() - verticalPadding);

        left = Integer.MAX_VALUE;
        right = 0;

        for (int i = top; i <= bottom; i++) {
            left = (int) Math.min(left, layout.getLineLeft(i));
            right = (int) Math.max(right, layout.getLineRight(i));
        }
    } else {
        left = 0;
        right = availableWidth;
    }

    final int actualWidth = right - left;

    if (actualWidth < availableWidth) {
        if (a == Alignment.ALIGN_CENTER) {
            x = left - ((availableWidth - actualWidth) / 2);
        } else if ((ltr && (a == Alignment.ALIGN_OPPOSITE)) || (a == Alignment.ALIGN_RIGHT)) {
            // align_opposite does NOT mean align_right, we need the paragraph
            // direction to resolve it to left or right
            x = left - (availableWidth - actualWidth);
        } else {
            x = left;
        }
    } else {
        x = Math.min(x, right - availableWidth);
        x = Math.max(x, left);
    }

    widget.scrollTo(x, y);
}
 
Example 28
Project: andlytics   File: Main.java View source code Vote up 6 votes
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	View rowView = convertView;
	if (rowView == null) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		rowView = inflater.inflate(textViewResourceId, parent, false);
	}

	TextView subtitle = (TextView) rowView.findViewById(android.R.id.text1);
	subtitle.setText(accounts.get(position).getName());
	Resources res = context.getResources();
	if (res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
		// Scale the text down slightly to fit on landscape due to the
		// shorter Action Bar
		// and additional padding due to the drop down
		// We don't use predefined values as it saves duplicating all of
		// the different display
		// configuration values from the ABS library
		float px = subtitle.getTextSize() * 0.9f;
		subtitle.setTextSize(px / (res.getDisplayMetrics().densityDpi / 160f));

	}

	// TODO In the future when accounts linked to multiple developer
	// consoles are supported
	// we can either merge all the apps together, or extend this adapter
	// to let the user select
	// account/console E.g:
	// account1
	// account2/console1
	// account2/console2
	// ...

	return rowView;
}
 
Example 29
Project: MDP-Group-10   File: MapGenerator.java View source code Vote up 6 votes
private int[][] getAccessToArena(GridLayout gv)
{
       int i=0;
   	int[ ][ ] tvArray = new int[15][20];
   	for (int k=0; k<15; k++){
   		for (int l =0; l<20; l++){
   			TextView child = (TextView)gv.getChildAt(i);
   			i++;
   			tvArray[k][l]=child.getId();
   		}
   	}
   	return tvArray;
}
 
Example 30
Project: android_packages_apps_IconFilterDesigner   File: FilterListAdapter.java View source code Vote up 6 votes
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
    TextView tv = (TextView) seekBar.getTag();
    AdjustableFilter f = (AdjustableFilter) tv.getTag();
    f.current = i + f.min;
    tv.setText("" + f.current);
}
 
Example 31
Project: RedditInPictures   File: LoginDialogFragment.java View source code Vote up 6 votes
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater lf = LayoutInflater.from(getActivity());
    View dialogView = lf.inflate(R.layout.login_dialog, null);

    if (getArguments() != null) {
        mUsername = BundleUtil.getString(getArguments(), Constants.Extra.EXTRA_USERNAME, null);
    }

    mUsernameText = (TextView) dialogView.findViewById(R.id.login_username);
    mPasswordText = (TextView) dialogView.findViewById(R.id.login_password);
    mPasswordText.setOnEditorActionListener(this);
    if (Strings.notEmpty(mUsername)) {
        mUsernameText.setText(mUsername);
        mPasswordText.requestFocus();
    } else {
        mUsernameText.requestFocus();
    }
    final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setView(dialogView)
                                                                     .setTitle(R.string.log_in_to_reddit)
                                                                     .setPositiveButton(R.string.log_in, null)
                                                                     .setNegativeButton(R.string.cancel, null)
                                                                     .create();
    // We have to override setOnShowListener here (min API level 8) in order to validate
    // the inputs before closing the dialog. Just overriding setPositiveButton closes the
    // automatically when the button is pressed
    dialog.setOnShowListener(getDialogOnShowListener());
    dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    mUsernameText.addTextChangedListener(this);
    mPasswordText.addTextChangedListener(this);
    return dialog;
}
 
Example 32
Project: notes   File: OTagsFlowView.java View source code Vote up 6 votes
private TextView getTag(String value) {
    TextView textView = new TextView(mContext);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    int padd = OResource.dimen(mContext, R.dimen.default_4dp);
    params.leftMargin = padd;
    textView.setPadding(padd, padd, padd, padd);
    textView.setLayoutParams(params);
    textView.setText(value);
    textView.setTag(value);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, OResource.dimen(mContext,
            R.dimen.text_size_xsmall));
    textView.measure(0, 0);
    textView.setBackgroundColor(Color.parseColor("#22000000"));
    textView.setTextColor(Color.BLACK);
    return textView;
}
 
Example 33
Project: kotoba-android   File: SentenceView.java View source code Vote up 6 votes
public View getView(View view)
{
    // Get sentence
    assert(m_id >= 0);
    if (m_info == null)
        m_info = m_app.Database().FileSentence().InfoEntry(m_id);

    // English
    TextView text_en = (TextView) view.findViewById(R.id.text_en);
    text_en.setText(m_info.TextEn());
    TextPaint tp = text_en.getPaint();

    // Japanese
    TextView text_jp_k = (TextView) view.findViewById(R.id.text_jp_k);
    FuriganaView text_jp_f = (FuriganaView) view.findViewById(R.id.text_jp_f);

    // Show either furigana or normal version
    if (m_show_furigana) {
        text_jp_f.setVisibility(View.VISIBLE);
        text_jp_k.setVisibility(View.GONE);
        int mark_s = -1;
        int mark_e = -1;
        if (m_sref != null) {
            mark_s = m_sref.Start();
            mark_e = m_sref.End();
        }
        text_jp_f.text_set(tp, m_info.TextJp(), mark_s, mark_e);
    } else {
        text_jp_f.setVisibility(View.GONE);
        text_jp_k.setVisibility(View.VISIBLE);
        String text = TextNormalize(m_info.TextJp());
        if (m_sref != null && m_sref.Start() >= 0 && m_sref.End() > m_sref.Start()) {
            SpannableString span = new SpannableString(text);
            span.setSpan(new StyleSpan(Typeface.BOLD), m_sref.Start(), m_sref.End(), 0);
            text_jp_k.setText(span);
        } else {
            text_jp_k.setText(text);
        }
    }

    // Return
    return view;
}
 
Example 34
Project: packages_apps_Mms   File: SlideListItemView.java View source code Vote up 6 votes
@Override
protected void onFinishInflate() {
    mTextPreview = (TextView) findViewById(R.id.text_preview);
    mTextPreview.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    mImagePreview = (ImageView) findViewById(R.id.image_preview);
    mAttachmentName = (TextView) findViewById(R.id.attachment_name);
    mAttachmentIcon = (ImageView) findViewById(R.id.attachment_icon);
}
 
Example 35
Project: BioWiki   File: TypefaceCache.java View source code Vote up 6 votes
protected static void setCustomTypeface(Context context, TextView view, AttributeSet attrs) {
    if (context == null || view == null)
        return;

    // skip at design-time
    if (view.isInEditMode())
        return;

    // read custom fontVariation from attributes, default to normal
    int variation = TypefaceCache.VARIATION_NORMAL;
    if (attrs != null) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WPTypeface, 0, 0);

        if (a != null) {
            try {
                variation = a.getInteger(R.styleable.WPTypeface_fontVariation, TypefaceCache.VARIATION_NORMAL);
            } finally {
                a.recycle();
            }
        }
    }

    // determine the font style from the existing typeface
    final int fontStyle;
    if (view.getTypeface() != null) {
        boolean isBold = view.getTypeface().isBold();
        boolean isItalic = view.getTypeface().isItalic();
        if (isBold && isItalic) {
            fontStyle = Typeface.BOLD_ITALIC;
        } else if (isBold) {
            fontStyle = Typeface.BOLD;
        } else if (isItalic) {
            fontStyle = Typeface.ITALIC;
        } else {
            fontStyle = Typeface.NORMAL;
        }
    } else {
        fontStyle = Typeface.NORMAL;
    }

    Typeface typeface = getTypeface(context, fontStyle, variation);
    if (typeface != null) {
        view.setTypeface(typeface);
    }
}
 
Example 36
Project: android-autofittextview   File: AutofitHelper.java View source code Vote up 6 votes
/**
 * Re-sizes the textSize of the TextView so that the text fits within the bounds of the View.
 */
private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
        int maxLines, float precision) {
    if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
        // Don't auto-size since there's no limit on lines.
        return;
    }

    int targetWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();
    if (targetWidth <= 0) {
        return;
    }

    CharSequence text = view.getText();
    TransformationMethod method = view.getTransformationMethod();
    if (method != null) {
        text = method.getTransformation(text, view);
    }

    Context context = view.getContext();
    Resources r = Resources.getSystem();
    DisplayMetrics displayMetrics;

    float size = maxTextSize;
    float high = size;
    float low = 0;

    if (context != null) {
        r = context.getResources();
    }
    displayMetrics = r.getDisplayMetrics();

    paint.set(view.getPaint());
    paint.setTextSize(size);

    if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
            || getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
        size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
                displayMetrics);
    }

    if (size < minTextSize) {
        size = minTextSize;
    }

    view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
}
 
Example 37
Project: Collageify   File: CreateGestureActivity.java View source code Vote up 6 votes
@SuppressWarnings({"UnusedDeclaration"})
public void addGesture(View v) {
    if (mGesture != null) {
        final TextView input = (TextView) findViewById(R.id.gesture_name);
        final CharSequence name = input.getText();
        if (name.length() == 0) {
            input.setError(getString(R.string.error_missing_name));
            return;
        }

        final GestureLibrary store = GestureBuilderActivity.getStore();
        store.addGesture(name.toString(), mGesture);
        store.save();

        setResult(RESULT_OK);

        final String path = new File(Environment.getExternalStorageDirectory(),
                "gestures").getAbsolutePath();
        Toast.makeText(this, getString(R.string.save_success, path), Toast.LENGTH_LONG).show();
    } else {
        setResult(RESULT_CANCELED);
    }

    finish();
    
}
 
Example 38
Project: androidtv-Leanback   File: GridItemPresenter.java View source code Vote up 6 votes
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
    TextView view = new TextView(parent.getContext());
    view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
    view.setFocusable(true);
    view.setFocusableInTouchMode(true);
    view.setBackgroundColor(mainFragment.getResources().getColor(R.color.default_background));
    view.setTextColor(Color.WHITE);
    view.setGravity(Gravity.CENTER);
    return new ViewHolder(view);
}
 
Example 39
Project: property-db   File: Linkify.java View source code Vote up 6 votes
private static final void addLinkMovementMethod(TextView t) {
    MovementMethod m = t.getMovementMethod();

    if ((m == null) || !(m instanceof LinkMovementMethod)) {
        if (t.getLinksClickable()) {
            t.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}
 
Example 40
Project: MD-BiliBili   File: AppUtils.java View source code Vote up 6 votes
public static void setTextWithLinks(TextView textView, String htmlText) {
    setHtmlText(textView, htmlText);
    textView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_UP ||
                    action == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();

                TextView widget = (TextView) v;
                x -= widget.getTotalPaddingLeft();
                y -= widget.getTotalPaddingTop();

                x += widget.getScrollX();
                y += widget.getScrollY();

                Layout layout = widget.getLayout();
                int line = layout.getLineForVertical(y);
                int off = layout.getOffsetForHorizontal(line, x);

                ClickableSpan[] link = Spannable.Factory.getInstance()
                        .newSpannable(widget.getText())
                        .getSpans(off, off, ClickableSpan.class);

                if (link.length != 0) {
                    if (action == MotionEvent.ACTION_UP) {
                        link[0].onClick(widget);
                    }
                    return true;
                }
            }
            return false;
        }
    });
}
 
Example 41
Project: notes   File: OTagsFlowView.java View source code Vote up 6 votes
private void generateView(Display display, List<String> tags) {
    Point point = new Point();
    display.getSize(point);
    int maxWidth = point.x;
    int widthSoFar = 20;
    LinearLayout layout = getRowView();
    for (String tag : tags) {
        TextView tagView = getTag(tag);
        widthSoFar += tagView.getMeasuredWidth();
        if (widthSoFar >= maxWidth) {
            addView(layout);
            layout = getRowView();
            layout.addView(tagView);
            widthSoFar = tagView.getMeasuredWidth();
        } else {
            layout.addView(tagView);
        }
    }
    addView(layout);
}
 
Example 42
Project: Heart   File: EditFragment.java View source code Vote up 6 votes
@Override
 public View onCreateView(LayoutInflater inflater,
                          ViewGroup container,
 			   Bundle savedInstanceState) {

   View result = inflater.inflate(R.layout.editfrag, null, false);

   date_field = (Button)result.findViewById(R.id.date);
   date_field.setOnClickListener(this);
   time_field = (TextView)result.findViewById(R.id.time);
   time_field.setOnClickListener(this);
   notes_field = (TextView)result.findViewById(R.id.notes);
   systolic_field = (NumberPicker)result.findViewById(R.id.systolic);
   systolic_field.setMaxValue(200);   // TODO -- what is a reasonable max?
   systolic_field.setMinValue(80);    // TODO -- what is a reasonable min?
   diastolic_field = (NumberPicker)result.findViewById(R.id.diastolic);
   diastolic_field.setMaxValue(200);   // TODO -- what is a reasonable max?
   diastolic_field.setMinValue(50);    // TODO -- what is a reasonable min?
   pulse_field = (NumberPicker)result.findViewById(R.id.pulse);
   pulse_field.setMaxValue(150);   // TODO -- what is a reasonable max?
   pulse_field.setMinValue(40);    // TODO -- what is a reasonable min?
   location = (RadioGroup)result.findViewById(R.id.location);
   side = (RadioGroup)result.findViewById(R.id.side);

   if (savedInstanceState != null) {
     // restore saved state (data & screen)
     if (BuildConfig.DEBUG) {
Log.v(TAG,"onCreateView: loading savedInstanceState");
     }
     date_time.setTimeInMillis(savedInstanceState.getLong(DatabaseHelper.DATE));
     setDateTimeText();
     systolic_field.setValue(savedInstanceState.getInt(DatabaseHelper.SYSTOLIC));
     diastolic_field.setValue(savedInstanceState.getInt(DatabaseHelper.DIASTOLIC));
     pulse_field.setValue(savedInstanceState.getInt(DatabaseHelper.PULSE));
   } else {
     // get data from myData object
     if (BuildConfig.DEBUG) {
Log.v(TAG,"onCreateView: no savedInstanceState");
     }
     updateView();
   }

   if (BuildConfig.DEBUG) {
     Log.v(TAG,"onCreateView: date_time: " + date_time.getTimeInMillis());
   }

   notes_field.requestFocus();
   return(result);
 }
 
Example 43
Project: unutopia-android   File: AboutActivity.java View source code Vote up 6 votes
private void enableLinksInText(int resId, String source) {
	final TextView view = (TextView) findViewById(resId);
	if (null == view) {
		return;
	}
	
	view.setFocusable(true);
	view.setLinksClickable(true);
	Linkify.addLinks(view, Linkify.ALL);
}
 
Example 44
Project: ics-openvpn   File: LogDialog.java View source code Vote up 6 votes
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
	if (savedInstanceState != null)
		log = savedInstanceState.getParcelable("log");
	final TextView text = new TextView(getActivity());
	text.setPadding(10, 10, 10, 10);
	text.setMovementMethod(new ScrollingMovementMethod());
	text.setTextIsSelectable(true);
	if (log != null)
		for (String s : log) {
			text.append(s + "\n");
		}
	else
		text.append("No Log");
	return new AlertDialog.Builder(getActivity())
			.setTitle(R.string.openvpn_log_dialog_title)
			.setIcon(android.R.drawable.ic_dialog_info).setView(text)
			.create();
}
 
Example 45
Project: NookPDFViewer   File: IconArrayAdapter.java View source code Vote up 6 votes
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = null;
    if (convertView == null) {
        LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
        row = inflater.inflate(m_ListItemId, parent, false);
    } else {
        row = convertView;
    }
    TextView label = (TextView) row.findViewById(m_TextFieldId);
    label.setText(getItem(position).toString());
    ImageView icon = (ImageView) row.findViewById(m_ImageFieldId);
    if (m_Icons.length > position && m_Icons[position] != -1) {
        icon.setImageResource(m_Icons[position]);
    } else {
        icon.setImageDrawable(null);
    }
    if (m_SubTextFieldId != -1) {
        TextView sub = (TextView) row.findViewById(m_SubTextFieldId);
        String val = m_SubTextValues[position];
        if (val != null) {
            sub.setText(val);
        } else {
            sub.setText(" ");
        }
        try {
            int oldidx = Integer.valueOf((String) sub.getHint());
            m_SubTextFields[oldidx] = null;
        } catch (Exception ex) {
        }
        sub.setHint(String.valueOf(position));
        m_SubTextFields[position] = sub;
    }
    if (m_EnableFields.length > position && !m_EnableFields[position]) {
        row.setVisibility(View.INVISIBLE);
    } else {
        row.setVisibility(View.VISIBLE);
    }
    return (row);
}
 
Example 46
Project: android-autofittextview   File: AutofitHelper.java View source code Vote up 6 votes
/**
 * Creates a new instance of [email protected] AutofitHelper} that wraps a [email protected] TextView} and enables
 * automatically sizing the text to fit.
 */
public static AutofitHelper create(TextView view, AttributeSet attrs, int defStyle) {
    AutofitHelper helper = new AutofitHelper(view);
    boolean sizeToFit = true;
    if (attrs != null) {
        Context context = view.getContext();
        int minTextSize = (int) helper.getMinTextSize();
        float precision = helper.getPrecision();

        TypedArray ta = context.obtainStyledAttributes(
                attrs,
                R.styleable.AutofitTextView,
                defStyle,
                0);
        sizeToFit = ta.getBoolean(R.styleable.AutofitTextView_sizeToFit, sizeToFit);
        minTextSize = ta.getDimensionPixelSize(R.styleable.AutofitTextView_minTextSize,
                minTextSize);
        precision = ta.getFloat(R.styleable.AutofitTextView_precision, precision);
        ta.recycle();

        helper.setMinTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
            .setPrecision(precision);
    }
    helper.setEnabled(sizeToFit);

    return helper;
}
 
Example 47
Project: android-formidable-validation   File: SetErrorHandler.java View source code Vote up 6 votes
private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) {
    int wid = tv.getPaddingLeft() + tv.getPaddingRight();
    int ht = tv.getPaddingTop() + tv.getPaddingBottom();

    //com.android.internal.R.dimen.textview_error_popup_default_width introduced after Gingerbread, only has one variant (240dip)
    int defaultWidthInPixels = mContext.getResources().getDimensionPixelSize(R.dimen.textview_error_popup_default_width);
    Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
    
    float max = 0;
    for (int i = 0; i < l.getLineCount(); i++) {
        max = Math.max(max, l.getLineWidth(i));
    }
    
    if(DEBUG) Log.d(TAG, "max: "+max+", height: "+l.getHeight());

    /*
     * Now set the popup size to be big enough for the text plus the border.
     */
    pop.setWidth(wid + (int) Math.ceil(max));
    pop.setHeight(ht + l.getHeight());	//TODO: buggy (the 2 shouldnt need to be there)
}
 
Example 48
Project: hashtag-view   File: HashtagView.java View source code Vote up 6 votes
private void decorateItemTextView(TextView textView) {
    textView.setTextColor(itemTextColor);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, itemTextSize);
    textView.setCompoundDrawablePadding(itemDrawablePadding);
    textView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, 0, rightDrawable, 0);
    textView.setEllipsize(ellipsizeList.get(itemTextEllipsize));
    if (maxItemWidth > 0) textView.setMaxWidth(maxItemWidth);
    if (typeface != null) textView.setTypeface(typeface);

    textView.setLayoutParams(itemFrameParams);
    textView.measure(0, 0);
}
 
Example 49
Project: android_packages_apps_AeroControl   File: AppMonitorDetailFragment.java View source code Vote up 6 votes
private void showLineTooltip(int entryIndex, Rect rect){

        mLineTooltip = (TextView) getActivity().getLayoutInflater().inflate(R.layout.circular_tooltip, null);
        mLineTooltip.setText((int)mLineChart.getData().get(0).getEntry(entryIndex).getValue() + "");

        LayoutParams layoutParams = new LayoutParams((int)Tools.fromDpToPx(64), (int)Tools.fromDpToPx(64));
        layoutParams.leftMargin = rect.centerX() - layoutParams.width/2;
        layoutParams.topMargin = rect.centerY() - layoutParams.height/2;
        mLineTooltip.setLayoutParams(layoutParams);

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1){
            mLineTooltip.setPivotX(layoutParams.width/2);
            mLineTooltip.setPivotY(layoutParams.height/2);
            mLineTooltip.setAlpha(0);
            mLineTooltip.setScaleX(0);
            mLineTooltip.setScaleY(0);
            mLineTooltip.animate()
                    .setDuration(150)
                    .alpha(1)
                    .scaleX(1).scaleY(1)
                    .rotation(360)
                    .setInterpolator(enterInterpolator);
        }

        mLineChart.showTooltip(mLineTooltip);
    }
 
Example 50
Project: Grinnell-DB-Android   File: DetailedSearchFragment.java View source code Vote up 6 votes
public void initializeViews(Context c) {
	firstNameText = (TextView) mView.findViewById(R.id.first_text);
	lastNameText = (TextView) mView.findViewById(R.id.last_text);
	usernameText = (TextView) mView.findViewById(R.id.username_text);
	phoneText = (TextView) mView.findViewById(R.id.phone_text);
	campusAddressText = (TextView) mView
			.findViewById(R.id.campus_address_text);
	homeAddressText = (TextView) mView.findViewById(R.id.home_address_text);
	facDeptSpinner = (Spinner) mView.findViewById(R.id.fac_dept_spinner);
	studentMajorSpinner = (Spinner) mView
			.findViewById(R.id.student_major_spinner);
	concentrationSpinner = (Spinner) mView
			.findViewById(R.id.concentration_spinner);
	sgaSpinner = (Spinner) mView.findViewById(R.id.sga_spinner);
	hiatusSpinner = (Spinner) mView.findViewById(R.id.hiatus_spinner);
	studentClassSpinner = (Spinner) mView
			.findViewById(R.id.student_class_spinner);

	editTextListener = new OnEditorActionListener() {
		@Override
		public boolean onEditorAction(TextView v, int actionId,
				KeyEvent event) {
			boolean handled = false;
			if (actionId == EditorInfo.IME_ACTION_SEARCH) {
				sendDetailedQuery();
				handled = true;
			}
			return handled;
		}
	};

	firstNameText.setOnEditorActionListener(editTextListener);
	lastNameText.setOnEditorActionListener(editTextListener);
	usernameText.setOnEditorActionListener(editTextListener);
	phoneText.setOnEditorActionListener(editTextListener);
	campusAddressText.setOnEditorActionListener(editTextListener);
	homeAddressText.setOnEditorActionListener(editTextListener);
}
 
Example 51
Project: sinaBlog   File: ViewHolderCommentList.java View source code Vote up 6 votes
public ViewHolderCommentList(View convertView, Context context) {
	/** find views */
	tv_text = (TextView) convertView.findViewById(R.id.tv_text);
	// ?????
	tv_text.setAutoLinkMask(Linkify.ALL);
	tv_text.setMovementMethod(LinkMovementMethod.getInstance());
	tv_text.setLinkTextColor(context.getResources().getColor(
			(R.color.light_blue)));
	tv_repost_text = (TextView) convertView
			.findViewById(R.id.tv_repost_text);
	tv_repost_text.setAutoLinkMask(Linkify.ALL);
	tv_repost_text.setMovementMethod(LinkMovementMethod.getInstance());
	tv_repost_text.setLinkTextColor(context.getResources().getColor(
			(R.color.light_blue)));
	tv_repost_name = (TextView) convertView
			.findViewById(R.id.tv_repost_name);

	tv_post_time = (TextView) convertView.findViewById(R.id.tv_post_time);
	tv_poster_name = (TextView) convertView
			.findViewById(R.id.tv_poster_name);
	iv_poster_avatar = (RoundCornerImageView) convertView
			.findViewById(R.id.iv_poster_avatar);
	iv_status_img = (ImageView) convertView
			.findViewById(R.id.iv_status_img);

}
 
Example 52
Project: notes   File: MailDetailDialog.java View source code Vote up 6 votes
private void init() {
    recordName = (TextView) findViewById(R.id.recordName);
    parent = (View) recordName.getParent();
    ODataRow row = mailMessage.browse(extra.getInt(OColumn.ROW_ID));
    attachments.addAll(row.getM2MRecord("attachment_ids").browseEach());
    if (attachments.size() > 0) {
        loadAttachments = new LoadAttachments();
        loadAttachments.execute();
    }
    horizontalScrollView = (LinearLayout) findViewById(R.id.attachmentsList);
    baseModel = OModel.get(this, row.getString("model"), mailMessage.getUser().getAndroidName());
    ODataRow record = baseModel.browse(baseModel.selectRowId(row.getInt("res_id")));
    String name = record.getString(baseModel.getDefaultNameColumn());
    recordName.setText(name);
    recordName.setBackgroundColor(OStringColorUtil.getStringColor(this, name));

    if (!row.getString("subject").equals("false"))
        OControls.setText(parent, R.id.messageSubject, row.getString("subject"));
    else
        OControls.setGone(parent, R.id.messageSubject);

    WebView messageBody = (WebView) findViewById(R.id.messageBody);
    messageBody.setBackgroundColor(Color.TRANSPARENT);
    messageBody.loadData(row.getString("body"), "text/html; charset=UTF-8", "UTF-8");

    Bitmap author_image = BitmapUtils.getAlphabetImage(this, row.getString("author_name"));
    String author_img = mailMessage.getAuthorImage(row.getInt(OColumn.ROW_ID));
    if (!author_img.equals("false")) {
        author_image = BitmapUtils.getBitmapImage(this, author_img);
    }
    OControls.setImage(parent, R.id.author_image, author_image);
    OControls.setText(parent, R.id.authorName, row.getString("author_name"));
    String date = ODateUtils.convertToDefault(row.getString("date"),
            ODateUtils.DEFAULT_FORMAT, "MMM dd, yyyy hh:mm a");
    OControls.setText(parent, R.id.messageDate, date);
}
 
Example 53
Project: plusTimer   File: CurrentSessionTimerFragment.java View source code Vote up 6 votes
public static int getTextViewHeight(TextView textView) {
    WindowManager wm =
            (WindowManager) textView.getContext().getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    int deviceWidth;

    Point size = new Point();
    display.getSize(size);
    deviceWidth = size.x;

    int widthMeasureSpec =
            View.MeasureSpec.makeMeasureSpec(deviceWidth, View.MeasureSpec.AT_MOST);
    int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    textView.measure(widthMeasureSpec, heightMeasureSpec);
    return textView.getMeasuredHeight();
}
 
Example 54
Project: Pure-File-Manager   File: EdgeLimitedMarqueeTextView.java View source code Vote up 6 votes
EdgeLimitedMarquee(final TextView view) {
    final Resources res = view.getResources();
    if (res == null) {
        throw new IllegalArgumentException("No Resources for view");
    }
    final float density = res.getDisplayMetrics().density;
    mScrollUnit = Math.round(MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION;
    mView = new WeakReference<>(view);
}
 
Example 55
Project: Rhythm   File: TextViewUtils.java View source code Vote up 6 votes
public static void setLeading(TextView view, int step, int leading) {
    // This is to make the behavior more deterministic: remove extra top/bottom padding
    view.setIncludeFontPadding(false);

    // Get font metrics and calculate required inter-line extra
    Paint.FontMetricsInt metrics = view.getPaint().getFontMetricsInt();
    final int extra = leading - metrics.descent + metrics.ascent;
    view.setLineSpacing(extra, 1);

    // Determine minimum required top extra so that the view lands on the grid
    final int alignTopExtra = (step + metrics.ascent % step) % step;
    // Determine minimum required bottom extra so that view bounds are aligned with the grid
    final int alignBottomExtra = (step - metrics.descent % step) % step;

    view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + alignTopExtra, view.getPaddingRight(), view.getPaddingBottom() + alignBottomExtra);
}
 
Example 56
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code Vote up 6 votes
/**
 * @see android.widget.TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable,
 *      Drawable, Drawable, Drawable)
 */
public static void setCompoundDrawablesRelativeWithIntrinsicBounds(TextView textView,
        Drawable start, Drawable top, Drawable end, Drawable bottom) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        textView.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, bottom, end);
    } else {
        textView.setCompoundDrawablesWithIntrinsicBounds(start, top, bottom, end);
    }
}
 
Example 57
Project: XposedGELSettings   File: DrawHook.java View source code Vote up 6 votes
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
	
	TextView iconText = (TextView) param.thisObject;
	color = iconText.getCurrentTextColor();
	iconText.setTextColor(Color.TRANSPARENT);
}
 
Example 58
Project: BetterBatteryStats   File: SeekBarPreference.java View source code Vote up 6 votes
/**
 * Update a SeekBarPreference view with our current state
 * @param view
 */
protected void updateView(View view) {

	try {
		mStatusText = (TextView) view.findViewById(R.id.seekBarPrefValue);

		mStatusText.setText(String.valueOf(mCurrentValue));
		mStatusText.setMinimumWidth(30);
		
		mSeekBar.setProgress(mCurrentValue - mMinValue);

		TextView unitsRight = (TextView)view.findViewById(R.id.seekBarPrefUnitsRight);
		unitsRight.setText(mUnitsRight);
		
		TextView unitsLeft = (TextView)view.findViewById(R.id.seekBarPrefUnitsLeft);
		unitsLeft.setText(mUnitsLeft);
		
	}
	catch(Exception e) {
		Log.e(TAG, "Error updating seek bar preference", e);
	}
	
}
 
Example 59
Project: packages_apps_Mms   File: ComposeMessageActivity.java View source code Vote up 6 votes
private Uri getSelectedUriFromMessageList(ListView listView, int position) {
    // If the context menu was opened over a uri, get that uri.
    MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position);
    if (msglistItem == null) {
        // FIXME: Should get the correct view. No such interface in ListView currently
        // to get the view by position. The ListView.getChildAt(position) cannot
        // get correct view since the list doesn't create one child for each item.
        // And if setSelection(position) then getSelectedView(),
        // cannot get corrent view when in touch mode.
        return null;
    }

    TextView textView;
    CharSequence text = null;
    int selStart = -1;
    int selEnd = -1;

    //check if message sender is selected
    textView = (TextView) msglistItem.findViewById(R.id.text_view);
    if (textView != null) {
        text = textView.getText();
        selStart = textView.getSelectionStart();
        selEnd = textView.getSelectionEnd();
    }

    // Check that some text is actually selected, rather than the cursor
    // just being placed within the TextView.
    if (selStart != selEnd) {
        int min = Math.min(selStart, selEnd);
        int max = Math.max(selStart, selEnd);

        URLSpan[] urls = ((Spanned) text).getSpans(min, max,
                                                    URLSpan.class);

        if (urls.length == 1) {
            return Uri.parse(urls[0].getURL());
        }
    }

    //no uri was selected
    return null;
}
 
Example 60
Project: devcoin-android   File: CurrencyAmountView.java View source code Vote up 6 votes
@Override
protected void onFinishInflate()
{
	super.onFinishInflate();

	final Context context = getContext();

	textView = (TextView) getChildAt(0);
	textView.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
	textView.setHintTextColor(lessSignificantColor);
	textView.setHorizontalFadingEdgeEnabled(true);
	textView.setSingleLine();
	setHint(null);
	setValidateAmount(textView instanceof EditText);
	textView.addTextChangedListener(textViewListener);
	textView.setOnFocusChangeListener(textViewListener);
	textView.setOnEditorActionListener(textViewListener);

	contextButton = new View(context)
	{
		@Override
		protected void onMeasure(final int wMeasureSpec, final int hMeasureSpec)
		{
			setMeasuredDimension(textView.getCompoundPaddingRight(), textView.getMeasuredHeight());
		}
	};
	final LayoutParams chooseViewParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
	chooseViewParams.gravity = Gravity.RIGHT;
	contextButton.setLayoutParams(chooseViewParams);
	this.addView(contextButton);

	updateAppearance();
}
 
Example 61
Project: Android_ShareSDK_Example_OAuth   File: PlatformGridView.java View source code Vote up 6 votes
private LinearLayout getView(int position, OnClickListener ocL, Context context) {
	Bitmap logo;
	String label;
	OnClickListener listener;
	if (beans[position] instanceof Platform) {
		logo = getIcon((Platform) beans[position]);
		label = getName((Platform) beans[position]);
		listener = ocL;
	} else {
		logo = ((CustomerLogo) beans[position]).logo;
		label = ((CustomerLogo) beans[position]).label;
		listener = ((CustomerLogo) beans[position]).listener;
	}

	LinearLayout ll = new LinearLayout(context);
	ll.setOrientation(LinearLayout.VERTICAL);

	ImageView iv = new ImageView(context);
	int dp_5 = cn.sharesdk.framework.utils.R.dipToPx(context, 5);
	iv.setPadding(dp_5, dp_5, dp_5, dp_5);
	iv.setScaleType(ScaleType.CENTER_INSIDE);
	LinearLayout.LayoutParams lpIv = new LinearLayout.LayoutParams(
			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	lpIv.setMargins(dp_5, dp_5, dp_5, dp_5);
	lpIv.gravity = Gravity.CENTER_HORIZONTAL;
	iv.setLayoutParams(lpIv);
	iv.setImageBitmap(logo);
	ll.addView(iv);

	TextView tv = new TextView(context);
	tv.setTextColor(0xffffffff);
	tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
	tv.setSingleLine();
	tv.setIncludeFontPadding(false);
	LinearLayout.LayoutParams lpTv = new LinearLayout.LayoutParams(
			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	lpTv.gravity = Gravity.CENTER_HORIZONTAL;
	lpTv.weight = 1;
	lpTv.setMargins(dp_5, 0, dp_5, dp_5);
	tv.setLayoutParams(lpTv);
	tv.setText(label);
	ll.addView(tv);
	ll.setOnClickListener(listener);

	return ll;
}
 
Example 62
Project: XposedGELSettings   File: TabHelperL.java View source code Vote up 6 votes
private void addTabInternal(final Tab tab, boolean focus) {
    if (DEBUG) log("Add tab " + tab.toString());

    TextView tabView = (TextView) inflater.inflate(R.layout.tab_layout, null, false);
    tabView.setId(tab.getLayoutId());
    tabView.setText(tab.getTitle());
    tabView.setTag(tab);
    tabView.setContentDescription(tab.getTitle());
    tabView.setOnLongClickListener(this);
    tabView.setOnClickListener(this);

    if (false) {// && PreferencesHelper.moveTabHostBottom) {
        tabView.setBackground(tabView.getContext().getResources().getDrawable(R.drawable.tab_indicator_background_bottom));
    }

    if (Common.PACKAGE_OBFUSCATED && Common.GNL_VERSION >= ObfuscationHelper.GNL_4_0_26
            && Color.alpha(tab.getPrimaryColor()) == 0) {

        tabView.setBackground(tabView.getContext().getResources().getDrawable(R.drawable.tab_indicator));
    }

    tabView.getBackground().setColorFilter(tab.getPrimaryColor(), PorterDuff.Mode.MULTIPLY);
    tabView.setTextColor(tab.getContrastColor());
    tabView.setTranslationY(hsv.getHeight() * 1.5f);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    if (tab.getIndex() != 0) {
        params.addRule(RelativeLayout.RIGHT_OF, tabs.get(tab.getIndex() - 1).getLayoutId());
        params.setMargins(-Utils.dpToPx(25), 0, 0, 0);
        tabView.setLayoutParams(params);
        hsv.requestLayout();
    }
    tabsContainer.addView(tabView);

    if (focus) {
        setCurrentTab(tab);
        scroll();
        animateShowTab(tabView, 0);
    }
}
 
Example 63
Project: OtRChat   File: ProviderListItem.java View source code Vote up 6 votes
public void init(Cursor c) {
    mProviderIcon = (ImageView) findViewById(R.id.providerIcon);
    mStatusIcon = (ImageView) findViewById(R.id.statusIcon);
    mProviderName = (TextView) findViewById(R.id.providerName);
    mLoginName = (TextView) findViewById(R.id.loginName);
    mChatView = (TextView) findViewById(R.id.conversations);
    mUnderBubble = findViewById(R.id.underBubble);
    mBubbleDrawable = getResources().getDrawable(R.drawable.bubble);
    mDefaultBackground = getResources().getDrawable(R.drawable.default_background);

    mProviderIdColumn = c.getColumnIndexOrThrow(Imps.Provider._ID);
    mProviderFullnameColumn = c.getColumnIndexOrThrow(Imps.Provider.FULLNAME);
    mActiveAccountIdColumn = c.getColumnIndexOrThrow(
            Imps.Provider.ACTIVE_ACCOUNT_ID);
    mActiveAccountUserNameColumn = c.getColumnIndexOrThrow(
            Imps.Provider.ACTIVE_ACCOUNT_USERNAME);
    mAccountPresenceStatusColumn = c.getColumnIndexOrThrow(
            Imps.Provider.ACCOUNT_PRESENCE_STATUS);
    mAccountConnectionStatusColumn = c.getColumnIndexOrThrow(
            Imps.Provider.ACCOUNT_CONNECTION_STATUS);

    mProviderNameColors = mProviderName.getTextColors();
    mLoginNameColors = mLoginName.getTextColors();
    mChatViewColors = mChatView.getTextColors();
}
 
Example 64
Project: silent-contacts-android   File: ContactListItemView.java View source code Vote up 6 votes
/**
 * Returns the text view for the contact name, creating it if necessary.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public TextView getNameTextView() {
    if (mNameTextView == null) {
        mNameTextView = new TextView(mContext);
        mNameTextView.setSingleLine(true);
        mNameTextView.setEllipsize(getTextEllipsis());
        mNameTextView.setTextAppearance(mContext, android.R.style.TextAppearance_Medium);
        // Manually call setActivated() since this view may be added after the first
        // setActivated() call toward this whole item view.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            mNameTextView.setActivated(isActivated());
        mNameTextView.setGravity(Gravity.CENTER_VERTICAL);
        addView(mNameTextView);
    }
    return mNameTextView;
}
 
Example 65
Project: radioflow   File: Notification.java View source code Vote up 6 votes
@SuppressLint("NewApi")
private void changeTextDirection(Builder dlg){
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    dlg.create();
    AlertDialog dialog =  dlg.show();
    if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
        TextView messageview = (TextView)dialog.findViewById(android.R.id.message);
        messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE);
    }
}
 
Example 66
Project: ProtocolAdapterManager   File: MainActivity.java View source code Vote up 6 votes
private void updateLog(String log) {
    Log.d(LOGTAG, log);

    final String fLog = log;

    final TextView tv = (TextView) findViewById(R.id.logBox);
    tv.post(new Runnable() {
        @Override
        public void run() {
            tv.append(fLog + "\n");
        }
    });

    final ScrollView sv = (ScrollView) findViewById(R.id.scrollBox);
    sv.postDelayed(new Runnable() {
        @Override
        public void run() {
            sv.fullScroll(ScrollView.FOCUS_DOWN);
        }
    }, 100L);

}
 
Example 67
Project: MHacksAndroid-Public   File: MainActivity.java View source code Vote up 6 votes
public void setUpTitleFont() {
    Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Gotham-BlackItalic.otf");

    try {
        Integer titleId = (Integer) Class.forName("com.android.internal.R$id").getField("action_bar_title").get(null);
        TextView title = (TextView) getWindow().findViewById(titleId);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) title.getLayoutParams();
        title.setTypeface(tf);

        int pixels = 5 * getResources().getDisplayMetrics().densityDpi / 160;
        params.setMargins(pixels, pixels, pixels, pixels);
        title.setLayoutParams(params);
        title.invalidate();
    } catch (Exception e) {
        Log.e("DERP", "Failed to obtain action bar title reference");
    }
}
 
Example 68
Project: otp-authenticator-android   File: AuthenticatorActivity.java View source code Vote up 6 votes
/**
 * Displays the user and OTP for the specified position. For HOTP, displays
 * the button for generating the next OTP value; for TOTP, displays the countdown indicator.
 */
@Override
public View getView(int position, View convertView, ViewGroup parent){
 LayoutInflater inflater = getLayoutInflater();
 PinInfo currentPin = getItem(position);

 View row;
 if (convertView != null) {
   // Reuse an existing view
   row = convertView;
 } else {
   // Create a new view
   row = inflater.inflate(R.layout.user_row, null);
 }
 TextView pinView = (TextView) row.findViewById(R.id.pin_value);
 TextView userView = (TextView) row.findViewById(R.id.current_user);
 View buttonView = row.findViewById(R.id.next_otp);
 CountdownIndicator countdownIndicator =
     (CountdownIndicator) row.findViewById(R.id.countdown_icon);

 if (currentPin.isHotp) {
   buttonView.setVisibility(View.VISIBLE);
   buttonView.setEnabled(currentPin.hotpCodeGenerationAllowed);
   ((ViewGroup) row).setDescendantFocusability(
       ViewGroup.FOCUS_BLOCK_DESCENDANTS); // makes long press work
   NextOtpButtonListener clickListener = new NextOtpButtonListener(currentPin);
   buttonView.setOnClickListener(clickListener);
   row.setTag(clickListener);

   countdownIndicator.setVisibility(View.GONE);
 } else { // TOTP, so no button needed
   buttonView.setVisibility(View.GONE);
   buttonView.setOnClickListener(null);
   row.setTag(null);

   countdownIndicator.setVisibility(View.VISIBLE);
   countdownIndicator.setPhase(mTotpCountdownPhase);
 }

 if (getString(R.string.empty_pin).equals(currentPin.pin)) {
   pinView.setTextScaleX(PIN_TEXT_SCALEX_UNDERSCORE); // smaller gap between underscores
 } else {
   pinView.setTextScaleX(PIN_TEXT_SCALEX_NORMAL);
 }
 pinView.setText(currentPin.pin);
 userView.setText(currentPin.user);

 return row;
}
 
Example 69
Project: Fairphone   File: Folder.java View source code Vote up 6 votes
protected boolean createAndAddShortcut(ShortcutInfo item) {
    final TextView textView =
        (TextView) mInflater.inflate(R.layout.application, this, false);
    textView.setCompoundDrawablesWithIntrinsicBounds(null,
            new FastBitmapDrawable(item.getIcon(mIconCache)), null, null);
    textView.setText(item.title);
    textView.setTag(item);

    textView.setOnClickListener(this);
    textView.setOnLongClickListener(this);

    // We need to check here to verify that the given item's location isn't already occupied
    // by another item.
    if (mContent.getChildAt(item.cellX, item.cellY) != null || item.cellX < 0 || item.cellY < 0
            || item.cellX >= mContent.getCountX() || item.cellY >= mContent.getCountY()) {
        // This shouldn't happen, log it. 
        Log.e(TAG, "Folder order not properly persisted during bind");
        if (!findAndSetEmptyCells(item)) {
            return false;
        }
    }

    CellLayout.LayoutParams lp =
        new CellLayout.LayoutParams(item.cellX, item.cellY, item.spanX, item.spanY);
    boolean insert = false;
    textView.setOnKeyListener(new FolderKeyEventListener());
    mContent.addViewToCellLayout(textView, insert ? 0 : -1, (int)item.id, lp, true);
    return true;
}
 
Example 70
Project: mpos-ui.android.paybutton   File: ApplicationSelectionFragment.java View source code Vote up 6 votes
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ApplicationInformation applicationInformation = mApplicationInformations.get(position);
    TextView tv = new TextView(getContext());
    tv.setText(applicationInformation.getApplicationName());
    tv.setTextAppearance(getContext(), android.R.style.TextAppearance_Medium);
    int padding = (int) getResources().getDimension(R.dimen.mpu_activity_horizontal_margin);
    tv.setPadding(padding, 0, padding, 0);
    tv.setMinHeight(UiHelper.dpToPx(getContext(), 52));
    tv.setGravity(Gravity.CENTER_VERTICAL);
    return tv;
}
 
Example 71
Project: android-unbound-dns   File: UnboundConfiguration.java View source code Vote up 6 votes
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.textarea, container, false);
    textarea = (TextView) v.findViewById(R.id.textarea);
    textarea.clearFocus();
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(getActivity().getFilesDir(), "package/bin/unbound.conf")));
        String line;
        while ((line = br.readLine()) != null) {
            textarea.append(line);
            textarea.append("\n");
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return v;
}
 
Example 72
Project: SmartTablayout   File: SmartTabLayout.java View source code Vote up 6 votes
/**
 * Create a default view to be used for tabs. This is called if a custom tab view is not set via
 * [email protected] #setCustomTabView(int, int)}.
 */
protected TextView createDefaultTabView(CharSequence title) {
  TextView textView = new TextView(getContext());
  textView.setGravity(Gravity.CENTER);
  textView.setText(title);
  textView.setTextColor(tabViewTextColors);
  textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabViewTextSize);
  textView.setTypeface(Typeface.DEFAULT_BOLD);
  textView.setLayoutParams(new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));

  if (tabViewBackgroundResId != NO_ID) {
    textView.setBackgroundResource(tabViewBackgroundResId);
  } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // If we're running on Honeycomb or newer, then we can use the Theme's
    // selectableItemBackground to ensure that the View has a pressed state
    TypedValue outValue = new TypedValue();
    getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
        outValue, true);
    textView.setBackgroundResource(outValue.resourceId);
  }

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
    textView.setAllCaps(tabViewTextAllCaps);
  }

  textView.setPadding(
      tabViewTextHorizontalPadding, 0,
      tabViewTextHorizontalPadding, 0);

  if (tabViewTextMinWidth > 0) {
    textView.setMinWidth(tabViewTextMinWidth);
  }

  return textView;
}
 
Example 73
Project: property-db   File: NumPadKey.java View source code Vote up 6 votes
@Override
public void onClick(View thisView) {
    if (mTextView == null) {
        if (mTextViewResId > 0) {
            final View v = NumPadKey.this.getRootView().findViewById(mTextViewResId);
            if (v != null && v instanceof TextView) {
                mTextView = (TextView) v;
            }
        }
    }
    // check for time-based lockouts
    if (mTextView != null && mTextView.isEnabled()) {
        mTextView.append(String.valueOf(mDigit));
    }
    doHapticKeyClick();
}
 
Example 74
Project: apteryx   File: StateLine.java View source code Vote up 6 votes
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
  top=getPaddingTop();
  left = getPaddingLeft();

  ImageView bullet = (ImageView)findViewById(BULLET_ID);
  TextView text = (TextView) findViewById(TEXT_ID);
  int localTop = (int) (text.getBaseline()-bullet.getMeasuredHeight() - 2* _mDensity);
  bullet.layout(left,localTop,left+bullet.getMeasuredWidth(),localTop+bullet.getMeasuredHeight());
  left+=bullet.getMeasuredWidth()+BULLET_PADDING* _mScaledDensity;
  text.layout(left,top,left+text.getMeasuredWidth(),top+text.getMeasuredHeight());
}
 
Example 75
Project: MediaBrowser.Android   File: AbstractMediaAdapter.java View source code Vote up 6 votes
/**
 * Sets thet top right overlay for an episode that is either missing or unaired.
 *
 * @param holder   The ViewHolder being affected
 * @param baseItem The item having it's watched state queried
 */
protected void setMissingOrUnairedEpisodeState(ViewHolder holder, BaseItemDto baseItem) {

    if (baseItem.getPremiereDate() != null) {

        Date premiereDate = Utils.convertToLocalDate(baseItem.getPremiereDate());

        long premiereDateMs = premiereDate.getTime();
        long currentMs = new Date().getTime();

        if (premiereDateMs - currentMs > 0) {
            holder.missingEpisodeOverlay.setText("UNAIRED");
        }

        holder.missingEpisodeOverlay.setVisibility(TextView.VISIBLE);
    }
}
 
Example 76
Project: Gui2Go   File: EditorActivity.java View source code Vote up 6 votes
private View createNewTextView() {
    TextView newWidget = new TextView(this);
    newWidget.setText("TextView");
    newWidget.setTextColor(Color.GRAY);
    newWidget.setOnDragListener(new OnDragListener() {
        @Override
        public boolean onDrag(View v, DragEvent event) {
            return false;
        }
    });
    return newWidget;
}
 
Example 77
Project: sdk-support   File: TextViewCompatJbMr1.java View source code Vote up 6 votes
public static void setCompoundDrawablesRelativeWithIntrinsicBounds(@NonNull TextView textView,
        @Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end,
        @Nullable Drawable bottom) {
    boolean rtl = textView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
    textView.setCompoundDrawablesWithIntrinsicBounds(rtl ? end : start, top, rtl ? start : end,
            bottom);
}
 
Example 78
Project: mytracks   File: MapSettingsActivity.java View source code Vote up 6 votes
/**
 * Configures the IME action done.
 * 
 * @param editTextPreference the edit text preference
 */
private void configImeActionDone(final EditTextPreference editTextPreference) {
  editTextPreference.getEditText()
      .setOnEditorActionListener(new TextView.OnEditorActionListener() {
          @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
          if (actionId == EditorInfo.IME_ACTION_DONE) {
            Dialog dialog = editTextPreference.getDialog();
            editTextPreference.onClick(dialog, Dialog.BUTTON_POSITIVE);
            dialog.dismiss();
            return true;
          }
          return false;
        }
      });
}
 
Example 79
Project: TestingStaff   File: DetailActivity.java View source code Vote up 6 votes
private void setupDetailBriefIntro(LinearLayout layout) {
	if (contentList != null) {
		if (contentList.size() == 0) {
			return;
		}
		final TextView detailTextView = new TextView(this);
		detailTextView.setTextColor(getResources().getColor(R.color.Fancl_Grey));
		detailTextView.setText(contentList.get(0));
		detailTextView.setTextSize(currentTextSize);

		ViewTreeObserver vto = detailTextView.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@Override
			public void onGlobalLayout() {
				ViewTreeObserver obs = detailTextView.getViewTreeObserver();
				obs.removeGlobalOnLayoutListener(this);
				if(detailTextView.getLineCount() > 10)
				{
					int lineEndIndex = detailTextView.getLayout().getLineEnd(9);
					String text = detailTextView.getText().subSequence(0, lineEndIndex-3) +"...";
					detailTextView.setText(text);
				}
			}
		});

		LinearLayout.LayoutParams textViewLayoutParams = new LinearLayout.LayoutParams(Math.round(DataUtil.dip2px(this, 280)), Math.round(DataUtil.dip2px(this, 190)));
		textViewLayoutParams.setMargins(0, Math.round(DataUtil.dip2px(this, 10)), 0, 0);
		textViewLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;

		layout.addView(detailTextView, textViewLayoutParams);
	}
}
 
Example 80
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code Vote up 6 votes
/**
 * @see android.widget.TextView#setCompoundDrawablesRelative(Drawable, Drawable, Drawable,
 *      Drawable)
 */
public static void setCompoundDrawablesRelative(TextView textView, Drawable start, Drawable top,
        Drawable end, Drawable bottom) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        textView.setCompoundDrawablesRelative(start, top, bottom, end);
    } else {
        textView.setCompoundDrawables(start, top, bottom, end);
    }
}
 
Example 81
Project: Ohmage_Phone   File: NumberPicker.java View source code Vote up 6 votes
@SuppressWarnings({"UnusedDeclaration"})
public NumberPicker(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs);
    setOrientation(VERTICAL);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.number_picker, this, true);
    mHandler = new Handler();
    InputFilter inputFilter = new NumberPickerInputFilter();
    mNumberInputFilter = new NumberRangeKeyListener();
    mIncrementButton = (NumberPickerButton) findViewById(R.id.increment);
    mIncrementButton.setOnClickListener(this);
    mIncrementButton.setOnLongClickListener(this);
    mIncrementButton.setNumberPicker(this);
    mDecrementButton = (NumberPickerButton) findViewById(R.id.decrement);
    mDecrementButton.setOnClickListener(this);
    mDecrementButton.setOnLongClickListener(this);
    mDecrementButton.setNumberPicker(this);

    mText = (TextView) findViewById(R.id.timepicker_text);
    mText.setOnFocusChangeListener(this);
    mText.setFilters(new InputFilter[] {inputFilter});
    mText.setRawInputType(InputType.TYPE_CLASS_NUMBER);

    if (!isEnabled()) {
        setEnabled(false);
    }

    mStart = DEFAULT_MIN;
    mEnd = DEFAULT_MAX;
}
 
Example 82
Project: property-db   File: ArrowKeyMovementMethod.java View source code Vote up 6 votes
@Override
protected boolean handleMovementKey(TextView widget, Spannable buffer, int keyCode,
        int movementMetaState, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_CENTER:
            if (KeyEvent.metaStateHasNoModifiers(movementMetaState)) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getRepeatCount() == 0
                        && MetaKeyKeyListener.getMetaState(buffer,
                                    MetaKeyKeyListener.META_SELECTING) != 0) {
                    return widget.showContextMenu();
                }
            }
            break;
    }
    return super.handleMovementKey(widget, buffer, keyCode, movementMetaState, event);
}
 
Example 83
Project: property-db   File: RequestRectangleVisibleWithInternalScroll.java View source code Vote up 6 votes
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.scroll_to_rect_with_internal_scroll);

    mTextBlob = (TextView) findViewById(R.id.blob);
    mTextBlob.scrollBy(0, scrollYofBlob);


    mScrollToBlob = (Button) findViewById(R.id.scrollToBlob);
    mScrollToBlob.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // the rect we want to make visible is offset to match
            // the internal scroll
            Rect rect = new Rect();
            rect.set(0, 0, 0, mTextBlob.getHeight());
            rect.offset(0, mTextBlob.getScrollY());
            mTextBlob.requestRectangleOnScreen(rect);
        }
    });
}
 
Example 84
Project: traffic-balance   File: RouteInfoLayer.java View source code Vote up 6 votes
@Override
public void initLayer(OsmandMapTileView view) {
	this.view = view;
	dm = new DisplayMetrics();
	WindowManager wmgr = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
	wmgr.getDefaultDisplay().getMetrics(dm);
	textSize = (int) (BASE_TEXT_SIZE * dm.density);
	
	uiHandler = new Handler();
	border = new RectF();
	paintBorder = new Paint();
	paintBorder.setARGB(220, 160, 160, 160);
	paintBorder.setStyle(Style.FILL);
	paintLightBorder = new Paint();
	paintLightBorder.setARGB(130, 220, 220, 220);
	paintLightBorder.setStyle(Style.FILL);
	paintBlack = new Paint();
	paintBlack.setARGB(255, 0, 0, 0);
	paintBlack.setStyle(Style.STROKE);
	paintBlack.setAntiAlias(true);
	
	textView = new TextView(view.getContext());
	LayoutParams lp = new LayoutParams(textSize, LayoutParams.WRAP_CONTENT);
	textView.setLayoutParams(lp);
	textView.setTextSize(16);
	textView.setTextColor(Color.argb(255, 0, 0, 0));
	textView.setMinLines(1);
	textView.setMaxLines(4);
	textView.setGravity(Gravity.CENTER_HORIZONTAL);
	textBorder = new RectF(-2, -1, textSize + 2, 0);
}
 
Example 85
Project: cardslib   File: NativeExpandPicassoFragment.java View source code Vote up 6 votes
@Override
public void setupInnerViewElements(ViewGroup parent, View view) {


    TextView tx = (TextView) view.findViewById(R.id.carddemo_inside_text);
    TextView tx1 = (TextView) view.findViewById(R.id.carddemo_inside_image_title1);
    TextView tx2 = (TextView) view.findViewById(R.id.carddemo_inside_image_title2);

    if (tx != null)
        tx.setText(""+randomNumber);

    //Rectangle Color. Only for test scope, use different colors
    final GradientDrawable rectangle=(GradientDrawable)tx.getBackground();
    if (rectangle!=null){
        if (randomNumber<1){
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color1));
        }else if (randomNumber<2){
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color2));
        }else if (randomNumber<3){
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color3));
        }else if (randomNumber<4){
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color4));
        }else if (randomNumber<5){
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color5));
        }else {
            rectangle.setColor(getResources().getColor(R.color.demoextra_card_background_color6));
        }
    }


    if (tx1 != null)
        tx1.setText("Detail............");

    if (tx2 != null)
        tx2.setText("xxxx xxx xxxx xxxxx");

}
 
Example 86
Project: Todayinformation   File: WelcomeActivity.java View source code Vote up 6 votes
/**
	 * ????????
	 */
	private void startAlphaAnimation(TextView textShow){
		if ( animation == null ) {
			// ????AlphaAnimation??  
			animation = new AlphaAnimation(0.01f, 1f);  
			// ????????????????  
			animation.setDuration(800);  
			// ?????? 
//			animation.setRepeatCount(5);
		}
		// ????????
		textShow.setAnimation(animation);
		// ???? 
		animation.start();
	}
 
Example 87
Project: my-ministry-assistant   File: HouseholderRecentActivityAdapter.java View source code Vote up 5 votes
@SuppressWarnings("deprecation")
@Override
public void bindView(View view, Context context, Cursor cursor) {
	ViewHolder holder = (ViewHolder) view.getTag();
	
	/** Title */
	holder.activity_title.setText(Phrase.from(context, R.string.activity_for_householder)
			.put("service", cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.ENTRY_TYPE_NAME)))
			.format().toString());
	
	/** Publications */
	if(cursor.getInt(cursor.getColumnIndex(UnionsNameAsRef.COUNT)) > 0) {
		holder.activity_publications.setVisibility(View.VISIBLE);
		holder.activity_publications.removeAllViews();
		
		database.openWritable();
		
		cursorpubs = database.fetchPlacedLitByTimeAndHouseholderID(cursor.getInt(cursor.getColumnIndex(Time._ID)), householderID);
		
		for(cursorpubs.moveToFirst();!cursorpubs.isAfterLast();cursorpubs.moveToNext()) {
			TextView valueTV = new TextView(context);
			valueTV.setText("(" + cursorpubs.getString(cursorpubs.getColumnIndex(LiteraturePlaced.COUNT)) + ") " + cursorpubs.getString(cursorpubs.getColumnIndex(LiteratureType.NAME)));
			valueTV.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(Helper.getIconResIDByLitTypeID(cursorpubs.getInt(cursorpubs.getColumnIndex(Literature.TYPE_OF_LIERATURE_ID)))), null, null, null);
			valueTV.setCompoundDrawablePadding(padding);
			valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
			valueTV.setTextAppearance(context, android.R.attr.textAppearanceMedium);
			valueTV.setTextColor(context.getResources().getColor(R.color.bg_card_title_text_holo_light));
			valueTV.setGravity(Gravity.CENTER_VERTICAL);
			
			holder.activity_publications.addView(valueTV);
		}
		
		cursorpubs.close();
		database.close();
	}
	else {
		holder.activity_publications.setVisibility(View.GONE);
	}
	
	/** Notes */
	if(TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(Notes.NOTES)))) {
		holder.activity_notes_layout.setVisibility(View.GONE);
	}
	else {
		holder.activity_notes_layout.setVisibility(View.VISIBLE);
		holder.activity_notes.setText(cursor.getString(cursor.getColumnIndex(Notes.NOTES)));
	}
	
	/** Date */
	if(cursor.getString(cursor.getColumnIndex(Time.DATE_START)) != null && cursor.getString(cursor.getColumnIndex(Time.DATE_START)).length() > 0) {
		String[] thedate = cursor.getString(cursor.getColumnIndex(Time.DATE_START)).split("-");
   		if(thedate.length == 3) {
   			/** We have the three numbers to make the date. Subtract 1 for zero based months. */ 
   			displayDate.set(Integer.valueOf(thedate[0]),Integer.valueOf(thedate[1])-1,Integer.valueOf(thedate[2]));
   			String date = DateUtils.formatDateTime(context, displayDate.getTimeInMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY);
   			
   			holder.activity_date.setText(Phrase.from(context, R.string.activity_date_by_publisher)
   					.put("date", date)
   					.put("publisher", cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.PUBLISHER_NAME)))
   					.format().toString());
   		}
   		else
   			holder.activity_date.setText(R.string.no_activity);
	}
	else
		holder.activity_date.setText(R.string.no_activity);
}
 
Example 88
Project: PTM-OSMGeotrigger   File: MapFragment.java View source code Vote up 5 votes
/**
 * Show a popup window with information about the feature.
 * @param feature The feature.
 */
private void showPopup(Graphic feature){
	Activity activity = getActivity();
	
	LinearLayout calloutLayout = new LinearLayout(activity);
	LinearLayout.LayoutParams calloutLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
	calloutLayout.setLayoutParams(calloutLayoutParams);
	calloutLayout.setOrientation(LinearLayout.VERTICAL);
	
	LinearLayout headerLayout = new LinearLayout(activity);
	LinearLayout.LayoutParams headerLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
	headerLayout.setLayoutParams(headerLayoutParams);
	headerLayout.setOrientation(LinearLayout.HORIZONTAL);
	headerLayout.setBackgroundColor(Color.YELLOW);
	
	TextView headerText = new TextView(activity);
	LinearLayout.LayoutParams headerTextLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
	headerText.setLayoutParams(headerTextLayoutParams);
	headerText.setPadding(12, 5, 12, 5);
	headerText.setTextColor(Color.rgb(0, 0, 0));
	headerText.setText("OSM Feature");
	headerText.setTextSize(15.0f);
	headerText.setTypeface(null, Typeface.BOLD);
	headerText.setBackgroundColor(Color.rgb(210, 210, 210));
	headerLayout.addView(headerText);
	
	TextView closeButton = new TextView(activity);
	LinearLayout.LayoutParams closeButtonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f);
	closeButton.setLayoutParams(closeButtonLayoutParams);
	closeButton.setPadding(18, 5, 18, 5);
	closeButton.setText("X");
	closeButton.setTextSize(15.0f);
	closeButton.setTypeface(null, Typeface.BOLD);
	closeButton.setBackgroundColor(Color.rgb(84, 145, 184));
	closeButton.setOnClickListener(new OnClickListener() {
		public void onClick(View v) {
			popup.hide();
		}
	});
	headerLayout.addView(closeButton);
	
	calloutLayout.addView(headerLayout);
	
	TableLayout table = new TableLayout(activity);
	TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT);
	table.setLayoutParams(layoutParams);
	
	String[] attrNames = feature.getAttributeNames();
	for(String attrName : attrNames){
		if(!attrName.equals("data")){
			Object attrValue = feature.getAttributeValue(attrName);
			TableRow row = new TableRow(activity);
			TextView nameText = new TextView(activity);
			nameText.setPadding(2, 1, 6, 0);
			nameText.setTextColor(Color.rgb(0, 0, 0));
			nameText.setText(attrName);
			nameText.setTextSize(15.0f);
			TextView valueText = new TextView(activity);
			valueText.setPadding(6, 1, 2, 0);
			valueText.setTextColor(Color.rgb(0, 0, 0));
			String value = attrValue != null ? attrValue.toString() : "";			
			valueText.setTextSize(15.0f);
			if(value.startsWith("http")){
				String url = "<a href=\"" + value + "\">" + this.getString(R.string.link_hint) + "</a>";
				valueText.setMovementMethod(LinkMovementMethod.getInstance());
				valueText.setText(Html.fromHtml(url));
			}else{
				valueText.setText(value);
			}
			row.addView(nameText);
			row.addView(valueText);
			table.addView(row);				
		}
	}
	calloutLayout.addView(table);
	
	popup = mapView.getCallout();
	popup.setContent(calloutLayout);
	Point mapPoint = null;
	Geometry geometry = feature.getGeometry();
	if(geometry.getType() == Geometry.Type.POINT){
		mapPoint = (Point)geometry;
	}else{
		Envelope env = new Envelope();
		geometry.queryEnvelope(env);
		mapPoint = env.getCenter();
	}
	mapView.centerAt(mapPoint, false);
	popup.show(mapPoint);
}
 
Example 89
Project: viaja-facil   File: ResultsActivity.java View source code Vote up 5 votes
private void updateConnection(ConnectionProxy conn, int groupPosition) {
	this.removeAllViews();
	int col = 0;
	for(LineProxy l : conn.getLines()) {
		if(col >= ViajaFacilActivity.NUM_COLORS) {
			col = col % ViajaFacilActivity.NUM_COLORS;
		}
		if(l.getType() != 0) {
			TextView line = new TextView(mContext);
			line.setText(l.getLinenum() + " ", BufferType.SPANNABLE);
			/*lineNum.setTextColor(getColor(col));
			lineNum.setTextSize(15);*/
			line.append(l.getRamal());
			Spannable str = line.getEditableText();
			str.setSpan(new RelativeSizeSpan(1.25f), 0, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			str.setSpan(new ForegroundColorSpan(getColor(col)), 0, l.getLinenum().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			col++;
			if(l.getAlternativeLines().size() > 0) {
				String alternativesText = " (" + mContext.getResources().getString(R.string.alternatives) + ": ";
				for(String s : l.getAlternativeLines()) {
					alternativesText += s + ", ";
				}
				alternativesText = alternativesText.substring(0, alternativesText.length() - 2);
				alternativesText += ")";
				int currLength = line.getText().length();
				line.append(alternativesText);
				Spannable str2 = line.getEditableText();
				str2.setSpan(new RelativeSizeSpan(0.75f), currLength, str2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				/*TextView alternatives = new TextView(mContext);
				alternatives.setText(alternativesText);
				alternatives.setTextSize(12);
				addView(alternatives, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));*/
			}
			addView(line, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			if(l.getStartStreet() != null && l.getDestStreet() != null) {
				String text = mContext.getResources().getString(R.string.from) + " " + l.getStartStreet();
				text += " " + mContext.getResources().getString(R.string.to) + " " + l.getDestStreet();
				TextView track = new TextView(mContext);
				track.setText(text, BufferType.SPANNABLE);
				track.append("");
				track.setMovementMethod(LinkMovementMethod.getInstance());
				track.setFocusable(false);
				int index1 = text.indexOf(l.getStartStreet());
				int index2 = text.indexOf(l.getDestStreet());
				Spannable str3 = track.getEditableText();
				str3.setSpan(new BackgroundColorSpan(R.color.lavender), index1, index1+l.getStartStreet().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				str3.setSpan(new BackgroundColorSpan(R.color.lavender), index2, index2+l.getDestStreet().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				str3.setSpan(new MyClickableSpan(new GeoPoint((int)(l.getRelevantPoints().get(0) * 1E6),(int)(l.getRelevantPoints().get(1) * 1E6)), groupPosition), index1, index1+l.getStartStreet().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				str3.setSpan(new MyClickableSpan(new GeoPoint((int)(l.getRelevantPoints().get(l.getRelevantPoints().size()-2) * 1E6),(int)(l.getRelevantPoints().get(l.getRelevantPoints().size()-1) * 1E6)), groupPosition), index2, index2+l.getDestStreet().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				addView(track, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			}
		}
	}
}
 
Example 90
Project: Gui2Go   File: SimpleStandardAdapter.java View source code Vote up 5 votes
@Override
public LinearLayout updateView(final View view,
		final TreeNodeInfo<Long> treeNodeInfo)
{
	// get handlers to the views
	final LinearLayout viewLayout = (LinearLayout) view;
	final TextView descriptionView = (TextView) viewLayout
			.findViewById(R.id.demo_list_item_description);
	final TextView levelView = (TextView) viewLayout
			.findViewById(R.id.demo_list_item_level);
	final TextView classView = (TextView) viewLayout
			.findViewById(R.id.demo_list_item_class);
	final ImageView classIconView = (ImageView) viewLayout
			.findViewById(R.id.tree_item_class_icon);
	final ImageView lockIconView = (ImageView) viewLayout
			.findViewById(R.id.tree_item_lock_icon);
	final CheckBox box = (CheckBox) viewLayout
			.findViewById(R.id.demo_list_checkbox);

	Long myID = treeNodeInfo.getId();
	// get the view represented by the tree item
	View myView = activity.findViewById(myID.intValue());
	// start setting the view properties
	CharSequence descText = (CharSequence) myView.getTag();
	descriptionView.setText(descText);
	classView.setText("("
			+ (CharSequence) myView.getClass().getSimpleName() + ")");
	levelView.setText(Integer.toString(treeNodeInfo.getLevel()));

	int classIconResourceId = determineClassIconResourceId(myView
			.getClass().getSimpleName());
	classIconView.setImageResource(classIconResourceId);

	if (!descText.equals("LayoutRoot")) {
		ExtrasClickListener mExtrasClickListener = new ExtrasClickListener();
		viewLayout.setOnClickListener(mExtrasClickListener);
		levelView.setOnClickListener(mExtrasClickListener);
		classView.setOnClickListener(mExtrasClickListener);
		descriptionView.setOnClickListener(mExtrasClickListener);
		lockIconView.setOnClickListener(mExtrasClickListener);
		classIconView.setOnClickListener(mExtrasClickListener);

		ExtrasLongClickListener mExtrasLongClickListener = new ExtrasLongClickListener();
		viewLayout.setOnLongClickListener(mExtrasLongClickListener);
		levelView.setOnLongClickListener(mExtrasLongClickListener);
		classView.setOnLongClickListener(mExtrasLongClickListener);
		descriptionView.setOnLongClickListener(mExtrasLongClickListener);
		lockIconView.setOnLongClickListener(mExtrasLongClickListener);
		classIconView.setOnLongClickListener(mExtrasLongClickListener);
	}

	box.setTag(treeNodeInfo.getId());
	if (treeNodeInfo.isWithChildren()) {
		box.setVisibility(View.INVISIBLE);
	} else {
		box.setVisibility(View.INVISIBLE);
		box.setChecked(selected.contains(treeNodeInfo.getId()));
	}
	box.setOnCheckedChangeListener(onCheckedChange);

	if (myView.getClass().getSuperclass() == ViewGroup.class
			|| myView.getClass() == TableLayout.class
			|| myView.getClass() == TableRow.class
			|| myView.getClass() == RadioGroup.class) {
		viewLayout.setOnDragListener(new LayoutDragListener());
	}

	return viewLayout;
}
 
Example 91
Project: BigPangOrderManager   File: WaterfallLayout.java View source code Vote up 5 votes
/**
 * ?
 * 1.N
 * 2.???
 * 3.
 */
private void createInnerViews(int flowNumber, Context context)
{
	this.flowLength = new int[flowNumber];
	for(int i = 0; i < this.flowLength.length; ++i)
	{
		this.flowLength[i] = 0;
	}
	
	LinearLayout llHorizontal = new LinearLayout(context);
	llHorizontal.setOrientation(LinearLayout.HORIZONTAL);
	llHorizontal.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	
	
	for(int i = 0; i < flowNumber; ++i)
	{
		LinearLayout inVertical = new LinearLayout(context);
		inVertical.setOrientation(LinearLayout.VERTICAL);
		inVertical.setLayoutParams(new LinearLayout.LayoutParams(1, LayoutParams.WRAP_CONTENT, 1.0f));
		
		// dummy view
		DummyView dv = new DummyView(context);
		dv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		dv.setBackgroundColor(Color.BLACK);
		inVertical.addView(dv);
		
		this.flowLayout.add(inVertical);
		llHorizontal.addView(inVertical);
	}
	TextView tv = new TextView(context);
	tv.setText(R.string.waterfall_tail);
	tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
	tv.setTextColor(Color.BLACK);
	tv.setGravity(Gravity.CENTER);
	tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	tv.setShadowLayer(2.0f, 2.0f, -2.0f, Color.parseColor("#73804055"));
	tv.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(R.drawable.loading_small), null, null);
	
	this.messageView = tv;
	
	LinearLayout llVertical = new LinearLayout(context);
	llVertical.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	llVertical.setOrientation(LinearLayout.VERTICAL);
	llVertical.addView(llHorizontal);
	llVertical.addView(tv);
	
	// ???????
	tv.setVisibility(View.INVISIBLE);
	
	this.picturesLayout = llHorizontal;
	
	// ?
	this.addView(llVertical);
	
	this.root = llVertical;
}
 
Example 92
Project: ReplicaIsland   File: ConversationDialogActivity.java View source code Vote up 5 votes
private void formatPages(Conversation conversation, TextView textView) {
   Paint paint = new Paint();
   final int maxWidth = textView.getWidth();
   final int maxHeight = textView.getHeight();
   paint.setTextSize(textView.getTextSize());
   paint.setTypeface(textView.getTypeface());

   for (int page = conversation.pages.size() - 1; page >= 0 ; page--) {
     ConversationUtils.ConversationPage currentPage = conversation.pages.get(page);
     CharSequence text = currentPage.text;
     // Iterate line by line through the text.  Add \n if it gets too wide,
     // and split into a new page if it gets too long.
     int currentOffset = 0;
     int textLength = text.length();
     SpannableStringBuilder spannedText = new SpannableStringBuilder(text);
     int lineCount = 0;
     final float fontHeight = -paint.ascent() + paint.descent();
     final int maxLinesPerPage = (int)(maxHeight / fontHeight);
     CharSequence newline = "\n";
     int addedPages = 0;
     int lastPageStart = 0;
     do {
int fittingChars = paint.breakText(text, currentOffset, textLength, true, maxWidth, null);

if (currentOffset + fittingChars < textLength) {
  fittingChars -= 2;
  // Text doesn't fit on line.  Insert a return after last space.
  int lastSpace = TextUtils.lastIndexOf(text, ' ', currentOffset + fittingChars - 1);
  if (lastSpace == -1) {
    // No spaces, just split at the last character.
    lastSpace = currentOffset + fittingChars - 1;
  }
  spannedText.replace(lastSpace, lastSpace + 1, newline, 0, 1);
  lineCount++;
  currentOffset = lastSpace + 1;
} else {
  lineCount++;
  currentOffset = textLength;
}

if (lineCount >= maxLinesPerPage || currentOffset >= textLength) {
  lineCount = 0;
  if (addedPages == 0) {
    // overwrite the original page
    currentPage.text = spannedText.subSequence(lastPageStart, currentOffset);
  } else {
    // split into a new page
    ConversationPage newPage = new ConversationPage();
    newPage.imageResource = currentPage.imageResource;
    newPage.text = spannedText.subSequence(lastPageStart, currentOffset);
    newPage.title = currentPage.title;
    conversation.pages.add(page + addedPages, newPage);
  }
  lastPageStart = currentOffset;
  addedPages++;
}
     } while (currentOffset < textLength);
   }

   // Holy crap we did a lot of allocation there.
   Runtime.getRuntime().gc();
 }
 
Example 93
Project: Subsonic   File: SelectDirectoryFragment.java View source code Vote up 5 votes
private void setupTextDisplay(final View header) {
	final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
	if(playlistName != null) {
		titleView.setText(playlistName);
	} else if(podcastName != null) {
		titleView.setText(podcastName);
		titleView.setPadding(0, 6, 4, 8);
	} else if(name != null) {
		titleView.setText(name);

		if(artistInfo != null) {
			titleView.setPadding(0, 6, 4, 8);
		}
	} else if(share != null) {
		titleView.setVisibility(View.GONE);
	}

	int songCount = 0;

	Set<String> artists = new HashSet<String>();
	Set<Integer> years = new HashSet<Integer>();
	Integer totalDuration = 0;
	for (Entry entry : entries) {
		if (!entry.isDirectory()) {
			songCount++;
			if (entry.getArtist() != null) {
				artists.add(entry.getArtist());
			}
			if(entry.getYear() != null) {
				years.add(entry.getYear());
			}
			Integer duration = entry.getDuration();
			if(duration != null) {
				totalDuration += duration;
			}
		}
	}

	final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
	if(podcastDescription != null || artistInfo != null) {
		artistView.setVisibility(View.VISIBLE);
		String text = podcastDescription != null ? podcastDescription : artistInfo.getBiography();
		Spanned spanned = null;
		if(text != null) {
			spanned = Html.fromHtml(text);
		}
		artistView.setText(spanned);
		artistView.setSingleLine(false);
		final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
		artistView.setLines(minLines);
		artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

		final Spanned spannedText = spanned;
		artistView.setOnClickListener(new View.OnClickListener() {
			@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@Override
			public void onClick(View v) {
				if(artistView.getMaxLines() == minLines) {
					// Use LeadingMarginSpan2 to try to make text flow around image
					Display display = context.getWindowManager().getDefaultDisplay();
					ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
					coverArtView.measure(display.getWidth(), display.getHeight());

					int height, width;
					ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView.getLayoutParams();
					if(coverArtView.getDrawable() != null) {
						height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
						width = coverArtView.getWidth() + coverArtView.getPaddingRight();
					} else {
						height = coverArtView.getHeight();
						width = coverArtView.getWidth() + coverArtView.getPaddingRight();
					}
					float textLineHeight = artistView.getPaint().getTextSize();
					int lines = (int) Math.ceil(height / textLineHeight);

					SpannableString ss = new SpannableString(spannedText);
					ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

					View linearLayout = header.findViewById(R.id.select_album_text_layout);
					RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout.getLayoutParams();
					int[]rules = params.getRules();
					rules[RelativeLayout.RIGHT_OF] = 0;
					params.leftMargin = vlp.rightMargin;

					artistView.setText(ss);
					artistView.setMaxLines(100);

					vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
					vlp.leftMargin = width;
				} else {
					artistView.setMaxLines(minLines);
				}
			}
		});
		artistView.setMovementMethod(LinkMovementMethod.getInstance());
	} else if(topTracks) {
		artistView.setText(R.string.menu_top_tracks);
		artistView.setVisibility(View.VISIBLE);
	} else if(showAll) {
		artistView.setText(R.string.menu_show_all);
		artistView.setVisibility(View.VISIBLE);
	} else if (artists.size() == 1) {
		String artistText = artists.iterator().next();
		if(years.size() == 1) {
			artistText += " - " + years.iterator().next();
		}
		artistView.setText(artistText);
		artistView.setVisibility(View.VISIBLE);
	} else {
		artistView.setVisibility(View.GONE);
	}

	TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
	TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
	if(podcastDescription != null || artistInfo != null) {
		songCountView.setVisibility(View.GONE);
		songLengthView.setVisibility(View.GONE);
	} else {
		String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount, songCount);
		songCountView.setText(s.toUpperCase());
		songLengthView.setText(Util.formatDuration(totalDuration));
	}
}
 
Example 94
Project: robotium-samples-srplayer-app   File: SRPlayer.java View source code Vote up 5 votes
private void UpdatePlayerVisibility(boolean Hide)
  {
  	View LayoutToHide = null;
  	View LayoutToShow = null;
  	Animation FadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
  	TextView tv = (TextView) findViewById(R.id.PageLabel);    	
  	
  	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean DisableAnim = prefs.getBoolean("AnimationDisable", false);
  	
  	if (!DisableAnim)
  		tv.startAnimation(FadeInAnimation);
  	
tv.setText(SRPlayer.currentStation.getStationName());
Button PlayerButton = (Button) findViewById(R.id.PlayerButton);
ScrollView sv = (ScrollView) findViewById(R.id.PlayerLayout);
RelativeLayout PageL = (RelativeLayout)findViewById(R.id.page_header_layout);
ViewGroup.MarginLayoutParams Layout = (MarginLayoutParams) sv.getLayoutParams();
		
final float scale = getBaseContext().getResources().getDisplayMetrics().density;		

if (Hide)
  	{						
	PageL.setBackgroundResource(R.drawable.black_gradient);
	
  		//Hide the player
  		LayoutToHide = (View)findViewById(R.id.PlayerLayout);
  		LayoutToHide.setVisibility(View.GONE);
  		
  		LayoutToHide = (View)findViewById(R.id.PlayerControlsLayout);
  		LayoutToHide.setVisibility(View.GONE);
  		
  		Animation SliedFromBottomAnimation = AnimationUtils.loadAnimation(this, R.anim.slidefrombottom);
  		//Animation SliedFromBottomAnimation = AnimationUtils.loadAnimation(this, R.anim.slidefromright);
  		//Show the listview
  		
  		if (CurrentAction != SRPlayer.ALARM)
  		{	
  			LayoutToHide = (View)findViewById(R.id.AlarmLayout);
      		LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToShow = (View)findViewById(R.id.ListViewLayout);
  			LayoutToShow.setVisibility(View.VISIBLE);
  		}
  		else
  		{    		
  			tv = (TextView) findViewById(R.id.PageLabel);
  	    	tv.setText("Alarm");
  	    	
  			UpdateAlarmView();
  			LayoutToShow = (View)findViewById(R.id.AlarmLayout);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToHide = (View)findViewById(R.id.ListViewLayout);
      		LayoutToHide.setVisibility(View.GONE);
  		}
  		    		
  		if (!DisableAnim)
  			LayoutToShow.startAnimation(SliedFromBottomAnimation);
  		
  		PlayerButton.setBackgroundResource(R.drawable.player);
  		
  		LayoutToHide = (View)findViewById(R.id.SeekLayout);
  		LayoutToHide.setVisibility(View.GONE);
  	}
  	else
  	{       		
  		//PageL.setBackgroundColor(android.R.color.transparent);
  		//PageL.setBackgroundResource(R.drawable.black_gradient);
  		    		    	    
  		PlayerButton.setBackgroundResource(R.drawable.player_pressed);
  		
  		Button ProgramButton = (Button) findViewById(R.id.ProgButton);
	Button CategoryButton = (Button) findViewById(R.id.PodCatButton);			    	
	Button FavoriteButton = (Button) findViewById(R.id.Favorites);			    	
	Button ChannelButton = (Button) findViewById(R.id.Channels);			    		
	
	ProgramButton.setBackgroundResource(R.drawable.channel_prog_select);
  		CategoryButton.setBackgroundResource(R.drawable.category);
  		FavoriteButton.setBackgroundResource(R.drawable.favorite);
  		ChannelButton.setBackgroundResource(R.drawable.channel);
  		
  		//Show the player
  		LayoutToShow = (View)findViewById(R.id.PlayerLayout);
  		LayoutToShow.setVisibility(View.VISIBLE);
  		if (!DisableAnim)
  			LayoutToShow.startAnimation(FadeInAnimation);
  		
  		LayoutToShow = (View)findViewById(R.id.PlayerControlsLayout);
  		LayoutToShow.setVisibility(View.VISIBLE);
  		if (!DisableAnim)
  			LayoutToShow.startAnimation(FadeInAnimation);
  		    		    		
  		//Hide the listview
  		LayoutToHide = (View)findViewById(R.id.ListViewLayout);
  		LayoutToHide.setVisibility(View.GONE);
  		
  		//Hide the AlarmLayout
  		LayoutToHide = (View)findViewById(R.id.AlarmLayout);
  		LayoutToHide.setVisibility(View.GONE);
  		
  		//Check the mode 
  		if (SRPlayer.currentStation.getStreamType() == Station.NORMAL_STREAM)
  		{
  			//Check if the channel is P1, P2, P3, P4 or any other
  			int ChannelBGID = R.drawable.black_gradient;
  			    			
  			switch (SRPlayer.currentStation.getChannelId())
  			{
  			case P1_CHANNELID : //P1
  				ChannelBGID = R.drawable.p1_gradient;
  				break;
  			case P2_CHANNELID : //P2
  				ChannelBGID = R.drawable.p2_gradient;
  				break;
  			case P3_CHANNELID : //P3
  				ChannelBGID = R.drawable.p3_gradient;
  				break;
  			case P4_CHANNELID : //P4
  				ChannelBGID = R.drawable.p4_gradient;
  				break;
  			case P4_SPORT_CHANNELID :
  				ChannelBGID = R.drawable.p4_gradient;
  				break;
  			default:    				
  				break;
  			}
  			
  			PageL.setBackgroundResource(ChannelBGID);
  			
  			//All text should be visible
  			LayoutToShow = (View)findViewById(R.id.NextProgramNamnLabel);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToShow = (View)findViewById(R.id.NextProgramNamn);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToShow = (View)findViewById(R.id.SongNamnLabel);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToShow = (View)findViewById(R.id.SongNamn);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToShow = (View)findViewById(R.id.NextSongNamnLabel);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			
  			LayoutToShow = (View)findViewById(R.id.NextSongNamn);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			    			 
  			Layout.bottomMargin = (int) (60 * scale);
  			sv.setLayoutParams(Layout);
  			
  			LayoutToHide = (View)findViewById(R.id.SeekLayout);
      		LayoutToHide.setVisibility(View.GONE);    			
  		}
  		else
  		{
  			PageL.setBackgroundResource(R.drawable.black_gradient);
  			
  			//All text should be visible
  			LayoutToHide = (View)findViewById(R.id.NextProgramNamnLabel);
  			LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToHide = (View)findViewById(R.id.NextProgramNamn);
  			LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToHide = (View)findViewById(R.id.SongNamnLabel);
  			LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToHide = (View)findViewById(R.id.SongNamn);
  			LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToHide = (View)findViewById(R.id.NextSongNamnLabel);
  			LayoutToHide.setVisibility(View.GONE);
  			
  			LayoutToHide = (View)findViewById(R.id.NextSongNamn);
  			LayoutToHide.setVisibility(View.GONE);
  			    			
  			Layout.bottomMargin = (int) (90 * scale);
  			sv.setLayoutParams(Layout);
  			
  			sv.setLayoutParams(Layout);
  			
  			LayoutToShow = (View)findViewById(R.id.SeekLayout);
  			LayoutToShow.setVisibility(View.VISIBLE);
  			if (!DisableAnim)
  				LayoutToShow.startAnimation(FadeInAnimation);
  			    			
  			UpdateSeekBar();
  		}
  	}
  }
 
Example 95
Project: mytracks   File: ListItemUtils.java View source code Vote up 5 votes
/**
 * Sets a list item.
 * 
 * @param activity the activity
 * @param view the list item view
 * @param isRecording true if recording
 * @param isPaused true if paused
 * @param iconId the icon id
 * @param iconContentDescriptionId the icon content description id
 * @param name the name value
 * @param sharedOwner if shared with me track, the owner, else null
 * @param totalTime the total time value
 * @param totalDistance the total distance value
 * @param markerCount the marker count
 * @param startTime the start time value
 * @param useRelativeTime true to display relative time if appropriate
 * @param category the category value
 * @param description the description value
 * @param photoUrl the photo url
 */
@SuppressWarnings("deprecation")
public static void setListItem(Activity activity, View view, boolean isRecording,
    boolean isPaused, int iconId, int iconContentDescriptionId, String name, String sharedOwner,
    String totalTime, String totalDistance, int markerCount, long startTime,
    boolean useRelativeTime, String category, String description, String photoUrl) {

  // Set photo
  ImageView photo = (ImageView) view.findViewById(R.id.list_item_photo);
  ImageView textGradient = (ImageView) view.findViewById(R.id.list_item_text_gradient);
  boolean hasPhoto = photoUrl != null && !photoUrl.equals("");

  photo.setVisibility(hasPhoto ? View.VISIBLE : View.GONE);
  textGradient.setVisibility(hasPhoto ? View.VISIBLE : View.GONE);

  if (hasPhoto) {
    int photoHeight = getPhotoHeight(activity);
    photo.getLayoutParams().height = photoHeight;
    photo.setImageResource(android.R.color.transparent);
    Display defaultDisplay = activity.getWindowManager().getDefaultDisplay();
    PhotoUtils.setImageVew(
        photo, Uri.parse(photoUrl), defaultDisplay.getWidth(), photoHeight, false);
  }
  
  // Set icon
  if (isRecording) {
    iconId = isPaused ? R.drawable.ic_track_paused : R.drawable.ic_track_recording;
    iconContentDescriptionId = isPaused ? R.string.image_pause : R.string.image_record;
  }

  ImageView iconImageView = (ImageView) view.findViewById(R.id.list_item_icon);
  iconImageView.setImageResource(iconId);
  iconImageView.setContentDescription(activity.getString(iconContentDescriptionId));

  // Set name
  TextView nameTextView = (TextView) view.findViewById(R.id.list_item_name);
  setTextView(activity, nameTextView, name, hasPhoto);

  // Set sharedOwner/totalTime/totalDistance
  TextView ownerTimeDistanceTextView = (TextView) view.findViewById(
      R.id.list_item_owner_time_distance);
  String ownerTimeDistance;
  if (isRecording) {
    ownerTimeDistanceTextView.setTextColor(activity.getResources()
        .getColor(isPaused ? android.R.color.white : R.color.recording_text));
    ownerTimeDistance = activity.getString(
        isPaused ? R.string.generic_paused : R.string.generic_recording);
  } else {
    // Match list_item_owner_time_distance in list_item.xml
    ownerTimeDistanceTextView.setTextAppearance(activity, R.style.TextSmall);
    ownerTimeDistance = getOwnerTimeDistance(sharedOwner, totalTime, totalDistance);
    if (markerCount > 0) {
      ownerTimeDistance += "  \u2027";
    }
  }
  setTextView(activity, ownerTimeDistanceTextView, ownerTimeDistance, hasPhoto);

  // Set markerCount
  ImageView markerCountIcon = (ImageView) view.findViewById(R.id.list_item_marker_count_icon);
  TextView markerCountTextView = (TextView) view.findViewById(R.id.list_item_marker_count);
  boolean hasMarker = markerCount > 0;
  markerCountIcon.setVisibility(hasMarker ? View.VISIBLE : View.GONE);
  String markerCountValue = hasMarker ? String.valueOf(markerCount) : null;
  if (hasMarker) {
    // Scale markerCountIcon
    int lineHeight = markerCountTextView.getLineHeight();
    LayoutParams layoutParams = markerCountIcon.getLayoutParams();
    layoutParams.width = lineHeight;
    layoutParams.height = lineHeight;
  }
  setTextView(activity, markerCountTextView, markerCountValue, hasPhoto);

  // Set date/time
  String[] dateTime = getDateTime(isRecording, activity, startTime, useRelativeTime);
  TextView dateTextView = (TextView) view.findViewById(R.id.list_item_date);
  setTextView(activity, dateTextView, dateTime[0], hasPhoto);

  TextView timeTextView = (TextView) view.findViewById(R.id.list_item_time);
  setTextView(activity, timeTextView, dateTime[1], hasPhoto);

  // Set category and description
  TextView categoryDescriptionTextView = (TextView) view.findViewById(
      R.id.list_item_category_description);
  String categoryDescription = isRecording ? null
      : StringUtils.getCategoryDescription(category, description);

  /*
   * Place categoryDescription in either ownerTimeDistanceTextView or
   * categoryDescriptionTextView
   */
  if (ownerTimeDistanceTextView.getVisibility() == View.GONE
      && markerCountIcon.getVisibility() == View.GONE) {
    setTextView(activity, categoryDescriptionTextView, null, hasPhoto);
    // Match list_item_category_description in list_item.xml
    ownerTimeDistanceTextView.setSingleLine(false);
    ownerTimeDistanceTextView.setMaxLines(2);
    setTextView(activity, ownerTimeDistanceTextView, categoryDescription, hasPhoto);
  } else {
    // Match list_item_owner_time_distance in list_item.xml
    ownerTimeDistanceTextView.setSingleLine(true);
    setTextView(activity, categoryDescriptionTextView, categoryDescription, hasPhoto);
  }

  // Adjust iconImageView layout gravity
  LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) iconImageView.getLayoutParams();
  params.gravity = ownerTimeDistanceTextView.getVisibility() == View.GONE
      && markerCountIcon.getVisibility() == View.GONE ? Gravity.TOP : Gravity.CENTER_VERTICAL;
}
 
Example 96
Project: android-money-manager-ex   File: SearchActivityTests.java View source code Vote up 5 votes
/**
     * Add two transaction for Dining Out. Search for this sub/category and confirm that the
     * results are shown and the total & currency match.
     */
    @Test
    public void searchForSubCategoryWorksWithData() {
        // arrange

        UnitTestHelper.setDefaultCurrency("BAM");
        DataHelpers.insertData();
        // add expected transaction
        DataHelpers.createTransaction(1, -1, TransactionTypes.Withdrawal, 2, 9, MoneyFactory.fromString("-14.68"));
        // add one more for testing the total calculation
        DataHelpers.createTransaction(1, -1, TransactionTypes.Withdrawal, 2, 9, MoneyFactory.fromString("-25.37"));

        //*******************************************
        // act

        // Click Select Category
        TextView selectCategory = (TextView) activity.findViewById(R.id.textViewSelectCategory);
        assertThat(selectCategory).isNotNull();
        selectCategory.performClick();

        // confirm that clicking the Select Category text view opens category selector
        ShadowActivity shadowActivity = Shadows.shadowOf(this.activity);
        Intent expectedIntent = shadowActivity.peekNextStartedActivityForResult().intent;
        assertThat(expectedIntent.getComponent()).isEqualTo(new ComponentName(this.activity,
                CategoryListActivity.class));
        assertThat(shadowActivity.getNextStartedActivity()).isEqualTo(expectedIntent);

        // Now simulate that we received the category.

        Fragment searchFragment = UnitTestHelper.getFragment(activity, SearchFragment.class.getSimpleName());
//        assertThat(searchFragment).isNotNull();

        // We "selected" Food:Dining out.
        Intent categoryData = UnitTestHelper.getSelectCategoryResult(2, "Food", 9, "Dining out");
        searchFragment.onActivityResult(SearchFragment.REQUEST_PICK_CATEGORY, Activity.RESULT_OK,
                categoryData);
        assertThat(selectCategory.getText()).containsSequence("Food : Dining out");

        // Run search

        LinearLayout searchButton = (LinearLayout) activity.findViewById(R.id.action_search);
        assertThat(searchButton).isNotNull();
        searchButton.performClick();

        //**************************************
        // assert

        // confirm the Total is shown and the sum is 0.

        Fragment resultsFragment = UnitTestHelper.getFragment(activity, AllDataListFragment.class.getSimpleName());
        assertThat(resultsFragment).isNotNull();

        View totalView = resultsFragment.getView().findViewById(R.id.textViewColumn1);
        assertThat(totalView).isNotNull();
        assertThat(totalView).isInstanceOf(TextView.class);
        TextView totalTextView = (TextView) totalView;
        assertThat(totalTextView.getText()).isEqualTo("Total");

        // total amount
        View totalNumberView = resultsFragment.getView().findViewById(R.id.textViewColumn2);
        assertThat(totalNumberView).isNotNull();
        assertThat(totalNumberView).isInstanceOf(TextView.class);
        TextView totalNumberTextView = (TextView) totalNumberView;
        assertThat(totalNumberTextView.getText()).isEqualTo("KM 40.05");
    }
 
Example 97
Project: Markers-Overlay   File: Markers_OverlayActivity.java View source code Vote up 5 votes
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    
    List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.red);
    Log.d("TextView", "****");
    Log.d("TextView", "Drawable width: " + drawable.getMinimumWidth() + " pixels and height: " + drawable.getMinimumHeight() + " pixels.");
    Log.d("TextView", "Drawable intrisinc width: " + drawable.getIntrinsicWidth() + " pixels and intrisinc height: " + drawable.getIntrinsicHeight() + " pixels.");
    MarkersItemizedOverlay itemizedoverlay = new MarkersItemizedOverlay(drawable, this);
    
    //Getting all information about the text being displayed    
    TextView textView = new TextView(this);
    textView.setText("123456");
    textView.setTextColor(0xFF000000);
    textView.layout(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    
    RelativeLayout relativeLayout = new RelativeLayout(this);
    relativeLayout.layout(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    relativeLayout.setBackgroundResource(R.drawable.red);
    relativeLayout.addView(textView);
    Bitmap viewBitmap = Bitmap.createBitmap(drawable.getMinimumWidth(), drawable.getMinimumHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(viewBitmap);
    relativeLayout.draw(canvas);
    BitmapDrawable bmd = new BitmapDrawable(viewBitmap);

    ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    imageView.layout(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    imageView.setImageBitmap(bmd.getBitmap());
    
    GeoPoint point = new GeoPoint(19240000,-99120000);
    OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
    overlayitem.setMarker(drawable);
    itemizedoverlay.addOverlay(overlayitem);
    mapOverlays.add(itemizedoverlay);
    
    //Map invisible
    mapView.setVisibility(mapView.INVISIBLE);
    
    float textViewSize = textView.getTextSize();
    float textViewScaleX = textView.getTextScaleX();
    Log.d("TextView", "***** You are writing: " + textView.getText());
    Log.d("TextView", "font size (pixel): " + textViewSize + " and text scale horizontally: " + textViewScaleX);
    //Padding?
    //Calculating total text size
    float textViewSizeX = textViewSize * textView.length() * textViewScaleX;
    Log.d("TextView", "Text size: " + textViewSizeX);
    float scale = getResources().getDisplayMetrics().density;
    Log.d("TextView", "Screen density scale: " + String.valueOf(scale));
}
 
Example 98
Project: property-db   File: Touch.java View source code Vote up 5 votes
/**
 * Handles touch events for dragging.  You may want to do other actions
 * like moving the cursor on touch as well.
 */
public static boolean onTouchEvent(TextView widget, Spannable buffer,
                                   MotionEvent event) {
    DragState[] ds;

    switch (event.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
        ds = buffer.getSpans(0, buffer.length(), DragState.class);

        for (int i = 0; i < ds.length; i++) {
            buffer.removeSpan(ds[i]);
        }

        buffer.setSpan(new DragState(event.getX(), event.getY(),
                        widget.getScrollX(), widget.getScrollY()),
                0, 0, Spannable.SPAN_MARK_MARK);
        return true;

    case MotionEvent.ACTION_UP:
        ds = buffer.getSpans(0, buffer.length(), DragState.class);

        for (int i = 0; i < ds.length; i++) {
            buffer.removeSpan(ds[i]);
        }

        if (ds.length > 0 && ds[0].mUsed) {
            return true;
        } else {
            return false;
        }

    case MotionEvent.ACTION_MOVE:
        ds = buffer.getSpans(0, buffer.length(), DragState.class);

        if (ds.length > 0) {
            if (ds[0].mFarEnough == false) {
                int slop = ViewConfiguration.get(widget.getContext()).getScaledTouchSlop();

                if (Math.abs(event.getX() - ds[0].mX) >= slop ||
                    Math.abs(event.getY() - ds[0].mY) >= slop) {
                    ds[0].mFarEnough = true;
                }
            }

            if (ds[0].mFarEnough) {
                ds[0].mUsed = true;
                boolean cap = (event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0
                        || MetaKeyKeyListener.getMetaState(buffer,
                                MetaKeyKeyListener.META_SHIFT_ON) == 1
                        || MetaKeyKeyListener.getMetaState(buffer,
                                MetaKeyKeyListener.META_SELECTING) != 0;
                float dx;
                float dy;
                if (cap) {
                    // if we're selecting, we want the scroll to go in
                    // the direction of the drag
                    dx = event.getX() - ds[0].mX;
                    dy = event.getY() - ds[0].mY;
                } else {
                    dx = ds[0].mX - event.getX();
                    dy = ds[0].mY - event.getY();
                }
                ds[0].mX = event.getX();
                ds[0].mY = event.getY();

                int nx = widget.getScrollX() + (int) dx;
                int ny = widget.getScrollY() + (int) dy;

                int padding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
                Layout layout = widget.getLayout();

                ny = Math.min(ny, layout.getHeight() - (widget.getHeight() - padding));
                ny = Math.max(ny, 0);
    
                int oldX = widget.getScrollX();
                int oldY = widget.getScrollY();

                scrollTo(widget, layout, nx, ny);

                // If we actually scrolled, then cancel the up action.
                if (oldX != widget.getScrollX() || oldY != widget.getScrollY()) {
                    widget.cancelLongPress();
                }

                return true;
            }
        }
    }

    return false;
}