根据要求,在onDraw()中使用画布设计的文本支持所有屏幕

the designed text using canvas in onDraw() as per reqirement to support all screens

本文关键字:文本 屏幕 支持 onDraw      更新时间:2023-09-26

我设计了一个侧边栏,它垂直包含26个字符。

当我使用HVGA屏幕(模拟器)时,它适合屏幕,但不适合其他屏幕。我使用onDraw()方法中的画布设计了那个侧边栏。

如何将此侧边栏适用于所有类型的屏幕?

private void init() {  
     float GESTURE_THRESHOLD_DP = 13.9f;
     // Get the screen's density scale
        float scale = getResources().getDisplayMetrics().density;
     // Convert the dps to pixels, based on density scale
     mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);
     // Use mGestureThreshold as a distance in pixels...
    l = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',  
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };  
    setBackgroundColor(0x44FFFFFF);  
}    
public SideBar(Context context, AttributeSet attrs, int defStyle) {  
    super(context, attrs, defStyle);  
    init();  
}  
public void setListView(ListView _list) {  
    list = _list;  
    sectionIndexter = (SectionIndexer) _list.getAdapter();  
}  
public boolean onTouchEvent(MotionEvent event) {  
    super.onTouchEvent(event);         
    int i = (int) event.getY();  
    System.out.println("i is:"+i);
    int idx = i / m_nItemHeight;      
    if (idx >= l.length) {  
        idx = l.length - 1;           
    } else if (idx < 0) {           
        idx = 0;  
    }  
    if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {         
        if (sectionIndexter == null) {              
            sectionIndexter = (SectionIndexer) list.getAdapter();  
        }  
        int position = sectionIndexter.getPositionForSection(l[idx]);           
        if (position == -1) {       
            return true;  
        }          
        list.setSelection(position);  
    }  
    return true;  
}
protected void onDraw(Canvas canvas) {  
    Paint paint = new Paint(); 
    float f;
    paint.setColor(Color.BLACK);  
    paint.setTextSize(18);  
   float scale = (float) getWidth();
   System.out.println(""+Paint.FAKE_BOLD_TEXT_FLAG);
    paint.setTextAlign(Paint.Align.CENTER);  
    paint.setAntiAlias(true);
    float widthCenter = getMeasuredWidth() /2;  
    for (int i = 0; i < l.length; i++) {  
        canvas.drawText(String.valueOf(l[i]), widthCenter, m_nItemHeight + (i * m_nItemHeight), paint);  
    }  
    super.onDraw(canvas);  
}
}  

发布onDraw()会有所帮助。无论如何,您必须使用getHeight() / 26作为参考来适应所有屏幕。你似乎是在不断地衡量问题。