2014-11-10 2 views
-1

Я занимаюсь строительством и андроидными приложениями, где я пользуюсь поисковым устройством для максимальной и минимальной стоимостью.Как получить значение SeekBar при использовании его в фрагменте?

я использовал пример по этой ссылке - http://www.kpbird.com/2011/05/android-seek-bar-with-two-thumb.html

Но когда я использую его в фрагменте деятельности я не могу получить SeekBar значения. Вот код, который я редактирую как потребность -

package tabsswipe; 

public class FragmentPlay extends Fragment { 

String selItem,selItem2,selItem3,selItem4; 
TextView tv1,tv2; 
SeekBarWithTwoThumb swtt; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_play, container, false); 

    getActivity().getActionBar().setBackgroundDrawable(
       new ColorDrawable(Color.parseColor("#0077d1"))); 
     ActionBar mActionBar = getActivity().getActionBar(); 
     getActivity().getActionBar().setIcon(
      new ColorDrawable(getResources().getColor(android.R.color.transparent)));  
     mActionBar.setDisplayShowHomeEnabled(true); 
     mActionBar.setDisplayShowTitleEnabled(false); 
     LayoutInflater mInflater = LayoutInflater.from(getActivity()); 
     View mCustomView = mInflater.inflate(R.layout.custom_actionbar2, null); 
     mActionBar.setCustomView(mCustomView); 
     mActionBar.setDisplayShowCustomEnabled(true); 

     ImageButton btn = (ImageButton) getActivity().findViewById(R.id.button); 
     btnt.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       viewCategory(); 

      } 
     }); 


    return rootView; 
    } 

    private void viewCategory() { 

     AlertDialog.Builder viewDialog = new AlertDialog.Builder(getActivity()); 

     viewDialog.setTitle("selecte"); 

     LayoutInflater li = (LayoutInflater) 
    getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View dialogView = li.inflate(R.layout.customealertdialogbox, null); 
     viewDialog.setView(dialogView); 

     viewDialog.setPositiveButton("Ok", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         new DownloadJSON().execute(); 
        } 
       }); 

     viewDialog.setNegativeButton("Cancel", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 

        } 
       }); 

     swtt = (SeekBarWithTwoThumb) dialogView.findViewById(R.id.myseekbar); 
     swtt.setSeekBarChangeListener(getActivity()); 

     //Button btn = (Button) dialogView.findViewById(R.id.button1); 
     //btn.setOnClickListener(new OnClickListener() { 

      //@Override 
      //public void onClick(View v) { 
       // TODO Auto-generated method stub 
       //Toast.makeText(getActivity(), "this is my Toast message!!! =)", 
         // Toast.LENGTH_LONG).show(); 
      //} 
    // }); 
     viewDialog.show(); 




    } 
    public class DatePickerFragment extends DialogFragment 
    implements DatePickerDialog.OnDateSetListener { 


    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the current date as the default date in the picker 
    final Calendar c = Calendar.getInstance(); 
    int year = c.get(Calendar.YEAR); 
    int month = c.get(Calendar.MONTH); 
    int day = c.get(Calendar.DAY_OF_MONTH); 
    Toast.makeText(getActivity(), year, 
       Toast.LENGTH_LONG).show(); 
    // Create a new instance of DatePickerDialog and return it 

    return new DatePickerDialog(getActivity(), this, year, month, day); 
    } 

    @Override 
    public void onDateSet(DatePicker view, int year, int month, int day) { 
    Calendar c = Calendar.getInstance(); 
    c.set(year, month, day); 

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
     String formattedDate = sdf.format(c.getTime()); 
    Toast.makeText(getActivity(), year, 
       Toast.LENGTH_LONG).show(); 
    } 

} 

}

Здесь есть искать бар библиотека -

package libseekbar; 

public class SeekBarWithTwoThumb extends ImageView { 

private String TAG = this.getClass().getSimpleName(); 
private Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.drawable.leftthumb); 
private int thumb1X, thumb2X; 
private int thumb1Value, thumb2Value; 
private int thumbY; 
private Paint paint = new Paint(); 
private int selectedThumb; 
private int thumbHalfWidth; 
private SeekBarChangeListener scl; 


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

public SeekBarWithTwoThumb(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

public SeekBarWithTwoThumb(Context context) { 
    super(context); 
} 

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    if (getHeight() > 0) 
     init(); 
} 

private void init() { 
    printLog("View Height =" + getHeight() + "\t\t Thumb Height :"+ thumb.getHeight()); 
    if (thumb.getHeight() > getHeight()) 
     getLayoutParams().height = thumb.getHeight(); 

    thumbY = (getHeight()/2) - (thumb.getHeight()/2); 
    printLog("View Height =" + getHeight() + "\t\t Thumb Height :"+ thumb.getHeight() + "\t\t" + thumbY); 

    thumbHalfWidth = thumb.getWidth()/2; 
    thumb1X = thumbHalfWidth; 
    thumb2X = getWidth()/2 ; 
    invalidate(); 
} 
public void setSeekBarChangeListener(SeekBarChangeListener scl){ 
    this.scl = scl; 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.drawBitmap(thumb, thumb1X - thumbHalfWidth, thumbY,paint); 
    canvas.drawBitmap(thumb, thumb2X - thumbHalfWidth, thumbY,paint); 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    int mx = (int) event.getX(); 
    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     if (mx >= thumb1X - thumbHalfWidth 
       && mx <= thumb1X + thumbHalfWidth) { 
      selectedThumb = 1; 
      printLog("Select Thumb 1"); 
     } else if (mx >= thumb2X - thumbHalfWidth 
       && mx <= thumb2X + thumbHalfWidth) { 
      selectedThumb = 2; 
      printLog("Select Thumb 2"); 
     } 
     break; 
    case MotionEvent.ACTION_MOVE: 
     printLog("Mouse Move : " + selectedThumb); 

     if (selectedThumb == 1) { 
      thumb1X = mx; 
      printLog("Move Thumb 1"); 
     } else if (selectedThumb == 2) { 
      thumb2X = mx; 
      printLog("Move Thumb 2"); 
     } 
     break; 
    case MotionEvent.ACTION_UP: 
     selectedThumb = 0; 
     break; 
    } 

    if(thumb1X < 0) 
     thumb1X = 0; 

    if(thumb2X < 0) 
     thumb2X = 0; 

    if(thumb1X > getWidth()) 
     thumb1X =getWidth() ; 

    if(thumb2X > getWidth()) 
     thumb2X =getWidth() ; 

    invalidate(); 
    if(scl !=null){ 
     calculateThumbValue(); 
     scl.SeekBarValueChanged(thumb1Value,thumb2Value); 
    } 
    return true; 
} 

private void calculateThumbValue(){ 
    thumb1Value = (100*(thumb1X))/(getWidth()); 
    thumb2Value = (100*(thumb2X))/(getWidth()); 
} 
private void printLog(String log){ 
    Log.i(TAG, log); 
} 

interface SeekBarChangeListener{ 
    void SeekBarValueChanged(int Thumb1Value,int Thumb2Value); 
} 

public void setSeekBarChangeListener(FragmentActivity activity, SeekBarChangeListener scl) { 
    // TODO Auto-generated method stub 
    this.scl = scl; 
} 
} 
+0

Где именно вы получаете значение SeekBar? – joao2fast4u

+0

@ joao2fast4u в поисковой строке замена –

ответ

0

@Hitesh Используйте этот код в диалоговом окне.

tv1.setText("Thumb 1 Value :" +Thumb1Value); 
    tv2.setText("Thumb 2 Value :"+Thumb2Value) ; 
+0

спасибо !! ................................ :) –

0

Как вы можете видеть, читая код библиотеки, он использует метод обратного вызова, чтобы уведомить вас, когда значения ползунка изменены (SeekBarValueChanged (int, int)).

Так что вам нужно сделать, это реализовать SeekBarChangeListener внутри фрагмента

public Class FragmentPlayo extends Fragment implements SeekBarChangeListener { 

, а затем реализовать метод (обратный вызов) внутри фрагмента, чтобы сделать все, что вы хотите делать, когда значения изменяются:

private void SeekBarValueChanged(int thumb1Value, int thumb2Value) { 
//Your code goes here when the values have changed 
} 

Надеюсь, это поможет!

Edit: Вы также должны добавить

swtt = (SeekBarWithTwoThumb) dialogView.findViewById(R.id.myseekbar); 
swtt.setSeekBarChangeListener(this); 

Как это означает, что «Эй, скажи мне, когда изменить значения, я буду заботиться о них!»

+0

сделано это !! все еще не работает –

+0

См. мое редактирование, вам нужно изменить swtt.setSeekBarChangeListener (getactivity()); to swtt.setSeekBarChangeListener (this) – NSimon

+0

Почему вы отмечаете двойной запуск в этом? –

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