2013-02-21 2 views
8

Я хочу, чтобы клиент панели поиска, как это изображение:Как сделать обычную строку поиска в андроиде?

enter image description here

я проверил this и this. Если у кого-нибудь есть представление об этом..пожалуйста, имейте это в виду. Спасибо

+1

проверить это http://stackoverflow.com/questions/12369519/how-to- set-the-seek-bar-thumb-with-a-layout-or-with-a-textview –

ответ

8

Если я правильно понял, вы хотите создать числовое значение выше фактического ползунка, который перемещается вдоль сферы.

Вы можете написать текст над фактическим изображением слайдера путем «слияния» текста непосредственно с вытягиваемым файлом изображения орба.

Я предполагаю, что вы используете first tutorial вы предоставили в оригинальном вопросе

public class CustomSeekBar extends Activity { 
    SeekBar mybar; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_custom_seek_bar); 
     mybar = (SeekBar) findViewById(R.id.seekBar1); 

     mybar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { 

     @Override 
     public void onStopTrackingTouch(SeekBar seekBar) { 

     //add here your implementation 
     } 

     @Override 
     public void onStartTrackingTouch(SeekBar seekBar) { 

     //add here your implementation 
     } 

     @Override 
     public void onProgressChanged(SeekBar seekBar, int progress, 
      boolean fromUser) { 
      int value = seekBar.getProgress(); //this is the value of the progress bar (1-100) 
      //value = progress; //this should also work 
      String valueString = value + ""; //this is the string that will be put above the slider 
      seekBar.setThumb(writeOnDrawable(R.drawable.thumbler_small, value));   
     } 
    }); 
    } 

    public BitmapDrawable writeOnDrawable(int drawableId, String text){ 

    Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true); 

    Paint paint = new Paint(); 
    paint.setStyle(Style.FILL); 
    paint.setColor(Color.BLACK); //Change this if you want other color of text 
    paint.setTextSize(20); //Change this if you want bigger/smaller font 

    Canvas canvas = new Canvas(bm); 
    canvas.drawText(text, 0, bm.getHeight()/2, paint); //Change the position of the text here 

    return new BitmapDrawable(bm); 
} 
} 

Это занимает вытяжку из ваших ресурсов рисует текст поверх него и возвращает новую вытяжку. Используйте seekBar.getProgress();, чтобы получить нужную вам информацию.

Я рекомендую немного очистить код, потому что теперь он создает новый объект краски каждый раз, когда вы касаетесь искателя, что очень плохо.

Вы должны были бы сделать больше материала, чтобы сделать его работу только при нажатии на шар, хотя ...

+0

Можете ли вы дать мне весь код ..? –

+0

У вас возникли проблемы с созданием вышеуказанного метода? –

+0

На самом деле я не могу понять этот код. Вот почему я прошу полный код .. Спасибо .. –

5

код XML

<SeekBar 
    android:id="@+id/seekBar1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:progressDrawable="@drawable/seek_bar" 
    android:paddingLeft="15dp" 
    android:paddingRight="15dp" 
    android:thumb="@drawable/thumbler_small" 
    android:indeterminate="false" /> 

seek_bar.xml

<?xml version="1.0" encoding="UTF-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     android:id="@+android:id/SecondaryProgress" 
     android:drawable="@drawable/first"/> 
    <item 
     android:id="@+android:id/progress" 
     android:drawable="@drawable/second"/> 
</layer-list> 

первая вытащенная пустая или показана не цветная полная площадь.

Вторая выдвижная - заполняемая или цветная полная площадь.

this ссылка поможет вам больше.

+0

sir Я получаю ошибку 'error: Ошибка: ресурс не найден, который соответствует указанному имени (в 'id' со значением '@ + android: id/SecondaryProgress').' – Gattsu

+1

maveň - Это изображения с индикацией прогресса с именем * * first ** и ** second **, которые хранятся в папке с возможностью переноса. – SChalice

1

Если вы хотите сделать то же самое, что и на изображении, вам нужно будет предоставить minHeight и maxHeight оба атрибута для поиска в вашем XML-файле. Например:

<SeekBar 
    android:id="@+id/seekBar1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:progressDrawable="@drawable/seek_bar" 
    android:paddingLeft="15dp" 
    android:paddingRight="15dp" 
    android:thumb="@drawable/thumbler_small" 
    **android:minHeight = "20dp" 
    android:maxHeight = "20dp"** 
    android:indeterminate="false" /> 

Пожалуйста, проверьте атрибуты в коде выше выделены.

5

Почему бы не написать пользовательский режим поиска.

Ниже приведен пример кода для размещения текста в середине слайдера большого пальца в области поиска, и текст перемещается с помощью ползунка. Должна быть легко адаптирована для печати текста поверх слайдера.

public class CustomSeekBar extends SeekBar { 

private Paint textPaint; 

private Rect textBounds = new Rect(); 

private String text = ""; 


public CustomSeekBar(Context context) { 
    super(context); 
    textPaint = new Paint(); 
    textPaint.setColor(Color.WHITE); 

} 

public CustomSeekBar(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    textPaint = new Paint(); 
    textPaint.setColor(Color.WHITE); 

} 

public CustomSeekBar(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 


    textPaint = new Paint(); 
    textPaint.setColor(Color.WHITE); 
     } 

@Override 
protected synchronized void onDraw(Canvas canvas) { 
    // First draw the regular progress bar, then custom draw our text 
    super.onDraw(canvas); 

    // Now progress position and convert to text. 
    text = Integer.toString(getProgress()); 

    // Now get size of seek bar. 
    float width = getWidth(); 
    float height = getHeight(); 

    // Set text size. 
    textPaint.setTextSize((height * 3)/4); 
    // Get size of text. 
    textPaint.getTextBounds(text, 0, text.length(), textBounds); 

    // Calculate where to start printing text. 
    float position = (width/getMax()) * getProgress(); 

    // Get start and end points of where text will be printed. 
    float textXStart = position - textBounds.centerX(); 
    float textXEnd = position + textBounds.centerX(); 

    // Check does not start drawing outside seek bar. 
    if(textXStart < 0) textXStart = 0; 

    if(textXEnd > width) 
     textXStart -= (textXEnd - width); 

    // Calculate y text print position. 
    float yPosition = (height/2) - textBounds.centerY(); //- (textBounds.bottom/2); 

    canvas.drawText(text, textXStart, yPosition, textPaint); 
} 

public synchronized void setTextColor(int color) { 
    super.drawableStateChanged(); 
    textPaint.setColor(color); 
    drawableStateChanged(); 
} 

}

Я надеюсь, что это полезным для вас.

0

привет сначала создать файл XML в вашей вытяжке папке (если не создать новый)
и вставить этот код или следовать tutorial, чтобы сделать это быстро, как это возможно

repeatbottombackground.xml

 <bitmap android:dither="true" android:src="@drawable/bottom_bar_repeat" android:tilemode="repeat"  xmlns:android="http://schemas.android.com/apk/res/android"> 

    </bitmap> 

seek_thumb.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:drawable="@drawable/seek_thumb_pressed" android:state_pressed="true" android:state_window_focused="true"> 

<item android:drawable="@drawable/seek_thumb_pressed" android:state_focused="true" android:state_window_focused="true"> 
<item android:drawable="@drawable/seek_thumb_pressed" android:state_selected="true" android:state_window_focused="true"> 
<item android:drawable="@drawable/seek_thumb_normal"> 
</item></item></item></item></selector> 

я даю вам link я надеюсь, что это са п поможет вам

К сожалению я не должен объяснить больше, просто следуйте учебник :)


приветом,

Смежные вопросы