So I have a view that has two edit texts that are using textwatchers as text change listeners. when the value from first edit text is changed a new value is calculated and set to the 2nd edit text and vice versa. I am removing the textwatchers before setting the text. the problem I am facing is when I type something in the first or the second edit text box it takes only one or two numbers and stops taking any input. the cursor goes from the end to the start. here is the class
public class CurrencyView extends RelativeLayout implements ICustomView{
private class CustomOnClick implements OnClickListener{
#Override
public void onClick(View v) {
final TextView view = (TextView)v;
final String options[] = ConversionTypes.getCurrencyTypes();
AlertDialog.Builder builder = new AlertDialog.Builder(rContext);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
view.setText(options[which]);
convert(view.getId());
}
});
builder.show();
}
}
private class CustomTextWatcher implements TextWatcher{
int ID;
#Override
public void afterTextChanged(Editable s) {
convert(ID);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if(s.toString().equals(type1Value.getText().toString())){
ID=11;
}
else{
ID=22;
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
}
private TextView currencyType1;
private LayoutParams currencyType1LP;
private TextView currencyType2;
private LayoutParams currencyType2LP;
private EditText type1Value;
private LayoutParams type1ValueLP;
private EditText type2Value;
private LayoutParams type2ValueLP;
private CustomTextWatcher fCustomTextWatcher = new CustomTextWatcher();
private ArrayList<Double> rates = new ArrayList<Double>();
private Context rContext;
private int screenWidth;
private ListView rPopularConversions;
private long lastRefreshed;
private TextView lastRefeshedView;
private void addListeners() {
currencyType1.setOnClickListener(new CustomOnClick());
currencyType2.setOnClickListener(new CustomOnClick());
addEditTextListeners();
}
private void addEditTextListeners() {
type1Value.addTextChangedListener(fCustomTextWatcher);
type2Value.addTextChangedListener(fCustomTextWatcher);
}
private void convert(int i) {
removeAllListeners();
if(i == 11 || i == 1 ){
if(!Formatting.isEmptyOrNull(type2Value)){
double from = rates.get(getLocation(currencyType2));
double to = rates.get(getLocation(currencyType1));
Currency c = new Currency(from,to, Double.valueOf(type2Value.getText().toString()));
type1Value.setText(String.valueOf(Formatting.roundOff(c.getResult())));
}
}
if(i == 22 || i==2 ){
if(!Formatting.isEmptyOrNull(type1Value)){
double from = rates.get(getLocation(currencyType1));
double to = rates.get(getLocation(currencyType2));
Currency c = new Currency(from, to, Double.valueOf(type1Value.getText().toString()));
type2Value.setText(String.valueOf(Formatting.roundOff(c.getResult())));
}
}
addEditTextListeners();
}
private int getLocation(TextView tv) {
for (int i = 0; i < ConversionTypes.getCurrencyTypes().length; i++) {
if(tv.getText().toString().equals(ConversionTypes.getCurrencyTypes()[i])){
return i;
}
}
return 0;
}
private void initialize() {
currencyType1 = CustomObject.getCustomTextView(rContext, 1, Color.parseColor("#63879F"), Color.WHITE, 16, ConversionTypes.getCurrencyTypes()[121]);
currencyType2 = CustomObject.getCustomTextView(rContext, 2, Color.parseColor("#63879F"), Color.WHITE, 16, ConversionTypes.getCurrencyTypes()[121]);
type1Value = CustomObject.getCustomInputBox(rContext, 35, "1", "Enter value", new int[]{}, 11);
type1Value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
type2Value = CustomObject.getCustomInputBox(rContext, 35, "1", "Enter value", new int[]{}, 22);
type2Value.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
int orientation = ((WindowManager) rContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
if (orientation == Surface.ROTATION_0 || orientation == Surface.ROTATION_180) {
loadPotraitView();
}
else {
loadLandscapeView();
}
}
#Override
public void loadLandscapeView() {
lastRefreshed = rContext.getSharedPreferences("com.rokzin.converto_preferences", 0).getLong("LastRefreshed", 0);
screenWidth = rContext.getResources().getDisplayMetrics().widthPixels;
removeAllViews();
rPopularConversions = new ListView(rContext);
RelativeLayout.LayoutParams listLP = CustomObject.getCustomParams(screenWidth, LayoutParams.WRAP_CONTENT, new int[]{});
listLP.addRule(RelativeLayout.BELOW, type2Value.getId());
currencyType1LP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.ALIGN_PARENT_TOP});
currencyType2LP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.ALIGN_PARENT_TOP});
type1ValueLP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT});
type2ValueLP = CustomObject.getCustomParams(screenWidth * 9/20, 120, new int[]{RelativeLayout.ALIGN_PARENT_RIGHT});
type1ValueLP.addRule(RelativeLayout.BELOW, currencyType1.getId());
type2ValueLP.addRule(RelativeLayout.BELOW, currencyType2.getId());
this.addView(currencyType1, currencyType1LP);
TextView equalTo = CustomObject.getCustomTextView(rContext, 111, Color.TRANSPARENT, Color.parseColor("#63879F"), 24, "=");
RelativeLayout.LayoutParams params = CustomObject.getCustomParams(screenWidth*2/20, 240, new int[]{RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.CENTER_HORIZONTAL});
equalTo.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
this.addView(equalTo, params);
this.addView(currencyType2, currencyType2LP);
this.addView(type1Value,type1ValueLP);
this.addView(type2Value,type2ValueLP);
this.addView(rPopularConversions,listLP);
removeAllListeners();
addListeners();
}
#Override
public void loadPotraitView() {
lastRefreshed = rContext.getSharedPreferences("com.rokzin.converto_preferences", 0).getLong("LastRefreshed", 0);
screenWidth = rContext.getResources().getDisplayMetrics().widthPixels;
removeAllViews();
rPopularConversions = new ListView(rContext);
RelativeLayout.LayoutParams listLP = CustomObject.getCustomParams(screenWidth, LayoutParams.WRAP_CONTENT, new int[]{});
listLP.addRule(RelativeLayout.BELOW, currencyType2.getId());
currencyType1LP = CustomObject.getCustomParams(screenWidth * 1/3, 120, new int[]{RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.ALIGN_PARENT_TOP});
currencyType2LP = CustomObject.getCustomParams(screenWidth * 1/3, 120, new int[]{});
type1ValueLP = CustomObject.getCustomParams(screenWidth * 2/3, 120, new int[]{RelativeLayout.ALIGN_PARENT_TOP});
type2ValueLP = CustomObject.getCustomParams(screenWidth * 2/3, 120, new int[]{});
type1ValueLP.addRule(RelativeLayout.RIGHT_OF, currencyType1.getId());
type2ValueLP.addRule(RelativeLayout.BELOW, currencyType1.getId());
currencyType2LP.addRule(RelativeLayout.RIGHT_OF, type2Value.getId());
currencyType2LP.addRule(RelativeLayout.BELOW, type1Value.getId());
this.addView(currencyType1, currencyType1LP);
this.addView(type1Value,type1ValueLP);
this.addView(type2Value,type2ValueLP);
this.addView(currencyType2, currencyType2LP);
this.addView(rPopularConversions,listLP);
removeAllListeners();
addListeners();
}
public void removeAllListeners(){
type1Value.removeTextChangedListener(fCustomTextWatcher);
type2Value.removeTextChangedListener(fCustomTextWatcher);
}
}
I think the problem is here:
if(s.toString().equals(type1Value.getText().toString())){
ID=11;
}
else{
ID=22;
}
Take in mind that both EditTexts are going through that method, so when type1Value is being edited, s.toString().equals(type1Value.getText().toString()) will be true.
I recommend you to use a TextWatcher for each EditText so you won't have to differentiate each one.
Related
I have read out many questions but I don't get the answer to mine.
So I am posting this new question.
I am working on a live streaming app. Basically I want to change the surface view size on click event like Whatsapp video calling.
I have two scenarios:-
Scenario 1:- One is relative layout which contains a surface view and there is a frame layout which also contains a surface view and I want to exchange when click event happens but the Click event listener is not working.
XML file
<FrameLayout
android:id="#+id/liveStreaming_videoAndControlsContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black">
<com.sos.GD_Live.utils.liveUtils.VideoGridContainer
android:id="#+id/liveStreaming_videoContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.sos.GD_Live.utils.liveUtils.VideoGridContainer>
<FrameLayout
android:id="#+id/videoChat_localVideoRender"
android:layout_marginBottom="130dp"
android:layout_marginRight="20dp"
android:layout_width="100dp"
android:onClick="frameclick"
android:visibility="visible"
android:layout_height="150dp"
android:layout_gravity="bottom|right"
/>
Its parent layout is also a frame layout
public class VideoGridContainer extends RelativeLayout implements Runnable {
private static final int MAX_USER = 4;
private static final int STAT_LEFT_MARGIN = 34;
private static final int STAT_TEXT_SIZE = 10;
private SparseArray<ViewGroup> mUserViewList = new SparseArray<>(MAX_USER);
private List<Integer> mUidList = new ArrayList<>(MAX_USER);
private Handler mHandler;
private int mStatMarginBottom;
private VideoViewEventListener mEventListener;
public VideoGridContainer(Context context) {
super(context);
init();
}
public VideoGridContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public VideoGridContainer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mHandler = new Handler(getContext().getMainLooper());
}
public void addUserVideoSurface(int uid, SurfaceView surface, boolean isLocal) {
if (surface == null) {
return;
}
int id = -1;
if (isLocal) {
if (mUidList.contains(0)) {
mUidList.remove((Integer) 0);
mUserViewList.remove(0);
}
if (mUidList.size() == MAX_USER) {
mUidList.remove(0);
mUserViewList.remove(0);
}
id = 0;
} else {
if (mUidList.contains(uid)) {
mUidList.remove((Integer) uid);
mUserViewList.remove(uid);
}
if (mUidList.size() < MAX_USER) {
id = uid;
}
}
if (id == 0) mUidList.add(0, uid);
else mUidList.add(uid);
if (id != -1) {
mUserViewList.append(uid, createVideoView(surface));
requestGridLayout();
}
}
private ViewGroup createVideoView(SurfaceView surface) {
RelativeLayout layout = new RelativeLayout(getContext());
layout.setId(surface.hashCode());
LayoutParams videoLayoutParams =
new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
layout.addView(surface, videoLayoutParams);
TextView text = new TextView(getContext());
text.setId(layout.hashCode());
LayoutParams textParams =
new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
textParams.bottomMargin = mStatMarginBottom;
textParams.leftMargin = STAT_LEFT_MARGIN;
text.setTextColor(Color.WHITE);
text.setTextSize(STAT_TEXT_SIZE);
layout.addView(text, textParams);
return layout;
}
public void removeUserVideo(int uid, boolean isLocal) {
if (isLocal && mUidList.contains(0)) {
mUidList.remove((Integer) 0);
mUserViewList.remove(0);
} else if (mUidList.contains(uid)) {
mUidList.remove((Integer) uid);
mUserViewList.remove(uid);
}
requestGridLayout();
if (getChildCount() == 0) {
mHandler.removeCallbacks(this);
}
}
private void requestGridLayout() {
removeAllViews();
layout(mUidList.size());
}
private void layout(int size) {
LayoutParams[] params = getParams(size);
for (int i = 0; i < size; i++) {
addView(mUserViewList.get(mUidList.get(i)), params[i]);
}
}
private LayoutParams[] getParams(int size) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
LayoutParams[] array =
new LayoutParams[size];
for (int i = 0; i < size; i++) {
if (i == 0) {
array[0] = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
array[0].addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
array[0].addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
} else if (i == 1) {
array[1] = new LayoutParams(width, height / 2);
array[0].height = array[1].height;
array[1].addRule(RelativeLayout.BELOW, mUserViewList.get(mUidList.get(0)).getId());
array[1].addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
} else if (i == 2) {
array[i] = new LayoutParams(width / 2, height / 2);
array[i - 1].width = array[i].width;
array[i].addRule(RelativeLayout.RIGHT_OF, mUserViewList.get(mUidList.get(i - 1)).getId());
array[i].addRule(RelativeLayout.ALIGN_TOP, mUserViewList.get(mUidList.get(i - 1)).getId());
} else if (i == 3) {
array[i] = new LayoutParams(width / 2, height / 2);
array[0].width = width / 2;
array[1].addRule(RelativeLayout.BELOW, 0);
array[1].addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
array[1].addRule(RelativeLayout.RIGHT_OF, mUserViewList.get(mUidList.get(0)).getId());
array[1].addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
array[2].addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
array[2].addRule(RelativeLayout.RIGHT_OF, 0);
array[2].addRule(RelativeLayout.ALIGN_TOP, 0);
array[2].addRule(RelativeLayout.BELOW, mUserViewList.get(mUidList.get(0)).getId());
array[3].addRule(RelativeLayout.BELOW, mUserViewList.get(mUidList.get(1)).getId());
array[3].addRule(RelativeLayout.RIGHT_OF, mUserViewList.get(mUidList.get(2)).getId());
}
}
return array;
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
clearAllVideo();
}
private void clearAllVideo() {
removeAllViews();
mUserViewList.clear();
mUidList.clear();
mHandler.removeCallbacks(this);
}
#Override
public void run() {
}
public void setItemEventHandler(VideoViewEventListener listener) {
this.mEventListener = listener;
}
}
This code where in Java file, when I added surface view for both of the layouts
mVideoLayout = findViewById(R.id.liveStreaming_videoContainer);
mVideoLayout.addUserVideoSurface(0, surface, true);
SurfaceView surface = prepareRtcVideo(remotehost, false);
surface.setZOrderMediaOverlay(true);
mCameraBtn.setVisibility(View.VISIBLE);
remotehostlist.add(remotehost);
surface.setZOrderOnTop(true);
runOnUiThread(() -> {
surface.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Toast.makeText(LiveStreamingActivity.this, "it's good", Toast.LENGTH_SHORT).show();
return true;
}
});
surface.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LiveStreamingActivity.this, "it's good", Toast.LENGTH_SHORT).show();
}
});
});
mLayoutSmallView.addView(surface);
mLayoutSmallView.setVisibility(View.VISIBLE);
mLayoutSmallView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
Toast.makeText(LiveStreamingActivity.this, "Focus changed", Toast.LENGTH_SHORT).show();
}
});
mRtcEngine.setupLocalVideo(new VideoCanvas(surface, VideoCanvas.RENDER_MODE_HIDDEN, 0));
mRtcEngine.enableVideo();
I have already tried onclick in XML, ontouchlistener, onfocuschange listener. But no one of them is working for it. Also tried is focusable.
The problem is I am unable to click the frame layout named mLayoutSmallView.
I want to switch the surface views when it is clicked.
I have a project where I use a horizontal recycler view and I want to center one element. My implementation works, but not in every case check this GIF here:
As you may note it scrolls correctly if I come from the left. If I come from the right it overscrolls a lot and I have no idea how to stop nor how to fix that.
I striped my code to this example here:
public class DemoActivity extends ActionBarActivity implements View.OnClickListener {
private static final int JUMP_TO_LEFT = MyAdapter.NON_VISIBLE_ITEMS + MyAdapter.VISIBLE_ITEMS - 1;
private static final int JUMP_TO_RIGHT = MyAdapter.NON_VISIBLE_ITEMS;
private LinearLayoutManager mLayoutManager;
private RecyclerView mRecycler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
findViewById(android.R.id.button1).setOnClickListener(this);
mRecycler = (RecyclerView)findViewById(R.id.recycler);
MyAdapter mAdapter = new MyAdapter();
mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mRecycler.setLayoutManager(mLayoutManager);
mRecycler.setHasFixedSize(true);
mRecycler.scrollToPosition(MyAdapter.NON_VISIBLE_ITEMS);
mRecycler.setAdapter(mAdapter);
}
#Override
public void onClick(View v) {
int pos = mLayoutManager.findFirstVisibleItemPosition();
int outer = (MyAdapter.VISIBLE_ITEMS - 1) / 2;
if(pos + outer >= MyAdapter.ITEM_IN_CENTER) {
mRecycler.smoothScrollToPosition(JUMP_TO_RIGHT);
} else {
mRecycler.smoothScrollToPosition(JUMP_TO_LEFT);
}
}
}
And here is my adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> implements View.OnClickListener {
public static final int VISIBLE_ITEMS = 7;
public static final int NON_VISIBLE_ITEMS = 150;
private static final int TOTAL_ITEMS = VISIBLE_ITEMS + NON_VISIBLE_ITEMS * 2;
public static final int ITEM_IN_CENTER = (int)Math.ceil(VISIBLE_ITEMS / 2f) + NON_VISIBLE_ITEMS;
private Calendar mCalendar;
public MyAdapter() {
mCalendar = GregorianCalendar.getInstance();
setHasStableIds(true);
}
private int getToday() {
return (int)TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
}
#Override
public int getItemCount() {
return TOTAL_ITEMS;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
final TextView tv = new TextView(parent.getContext());
int width = parent.getWidth() / VISIBLE_ITEMS;
tv.setLayoutParams(new TableRow.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT, 1));
tv.setGravity(Gravity.CENTER);
tv.setBackgroundColor(Color.TRANSPARENT);
DisplayMetrics metrics = tv.getContext().getResources().getDisplayMetrics();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, metrics);
tv.setLineSpacing(padding, 1f);
tv.setPadding(0, (int)padding, 0, 0);
tv.setOnClickListener(this);
return new Holder(tv);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
int today = getToday();
mCalendar.setTimeInMillis(System.currentTimeMillis());
mCalendar.set(Calendar.HOUR_OF_DAY, 12); // set to noon to avoid energy saver time problems
mCalendar.add(Calendar.DAY_OF_YEAR, position - ITEM_IN_CENTER + 1);
DateFormat format = new SimpleDateFormat("E\nd");
String label = format.format(mCalendar.getTime()).replace(".\n", "\n");
int day = (int)TimeUnit.MILLISECONDS.toDays(mCalendar.getTimeInMillis());
holder.update(day, today, label);
}
#Override
public long getItemId(int position) {
mCalendar.setTimeInMillis(System.currentTimeMillis());
mCalendar.set(Calendar.HOUR_OF_DAY, 12); // set to noon to avoid energy saver time problems
mCalendar.add(Calendar.DAY_OF_YEAR, position - ITEM_IN_CENTER + 1);
DateFormat format = new SimpleDateFormat("dMMyyyy");
return Long.parseLong(format.format(mCalendar.getTime()));
}
#Override
public void onClick(View v) {
String day = ((TextView)v).getText().toString().replace("\n", " ");
Toast.makeText(v.getContext(), "You clicked on " + day, Toast.LENGTH_SHORT).show();
}
public class Holder extends RecyclerView.ViewHolder {
private final Typeface font;
private Holder(TextView v) {
super(v);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
font = Typeface.create("sans-serif-light", Typeface.NORMAL);
} else {
font = null;
}
}
public void update(int day, int today, String label) {
TextView tv = (TextView)itemView;
tv.setText(label);
if(day == today) {
tv.setTextSize(18);
tv.setTypeface(null, Typeface.BOLD);
} else {
tv.setTextSize(16);
tv.setTypeface(font, Typeface.NORMAL);
}
tv.setBackgroundColor(0xff8dc380);
}
}
}
Do you see a reason for that? To make it simpler for you I also put this code on GitHub. https://github.com/rekire/RecylcerViewBug
I found a surprising simple workaround:
#Override
public void onClick(View v) {
int pos = mLayoutManager.findFirstVisibleItemPosition();
int outer = (MyAdapter.VISIBLE_ITEMS + 1) / 2;
int delta = pos + outer - ForecastAdapter.ITEM_IN_CENTER;
//Log.d("Scroll", "delta=" + delta);
View firstChild = mForecast.getChildAt(0);
if(firstChild != null) {
mForecast.smoothScrollBy(firstChild.getWidth() * -delta, 0);
}
}
Here I calculate the width to jump myself, that does exactly what I want.
In case of LinearLayoutManager with vertical orientation you can create own SmoothScroller and override calculateDyToMakeVisible() method where you can set desired view position. For example, to make the target view always to be appeared at the top side of RecyclerView after smoothScroll() write this:
class CustomLinearSmoothScroller extends LinearSmoothScroller {
public CustomLinearSmoothScroller(Context context) {
super(context);
}
#Override
public int calculateDyToMakeVisible(View view, int snapPreference) {
final RecyclerView.LayoutManager layoutManager = getLayoutManager();
if (!layoutManager.canScrollVertically()) {
return 0;
}
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)view.getLayoutParams();
final int top = layoutManager.getDecoratedTop(view) - params.topMargin;
final int bottom = layoutManager.getDecoratedBottom(view) + params.bottomMargin;
final int viewHeight = bottom - top;
final int start = layoutManager.getPaddingTop();
final int end = start + viewHeight;
return calculateDtToFit(top, bottom, start, end, snapPreference);
}
"top" and "bottom" - bounds of the target view
"start" and "end" - points between which the view should be placed during smoothScroll
This worked for me:
itemsView.smoothScrollBy(-recyclerView.computeHorizontalScrollOffset(), 0)
To support smooth scrolling, you must override
smoothScrollToPosition(RecyclerView, State, int) and create a
RecyclerView.SmoothScroller.
RecyclerView.LayoutManager is responsible
for creating the actual scroll action. If you want to provide a custom
smooth scroll logic, override smoothScrollToPosition(RecyclerView,
State, int) in your LayoutManager.
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html#smoothScrollToPosition(int)
In your case, use smoothScrollBy could be a workaround (doesn't need this override).
I am making horizontal scrollview gallery, and I want to autoscroll it. Now it's scrolling from left to right but when I reach end of list I just simply jump to first one, but it looks really bad, so I want to go scroll around from beginning avoiding just skipping to first one, or if it is not possible just start scrolling to the other side when I reach last view on right (maybe better option). Could someone help me how to do this?
private LinearLayout horizontalOuterLayout;
private HorizontalScrollView horizontalScrollview;
private int scrollMax;
private int scrollPos = 0;
private TimerTask clickSchedule;
private TimerTask scrollerSchedule;
private TimerTask faceAnimationSchedule;
private Timer scrollTimer = null;
private Timer faceTimer = null;
private String[] imageNameArray ={ "sponsors_czarnykot", "sponsors_estradarzeszow","sponsors_klubp","sponsors_kula","sponsors_czarnykot", "sponsors_estradarzeszow","sponsors_klubp","sponsors_kula" };
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.horizontal_layout);
horizontalScrollview = (HorizontalScrollView) findViewById(R.id.horiztonal_scrollview_id);
horizontalOuterLayout = (LinearLayout) findViewById(R.id.horiztonal_outer_layout_id);
horizontalScrollview.setHorizontalScrollBarEnabled(false);
addImagesToView();
ViewTreeObserver vto = horizontalOuterLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
horizontalOuterLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScrollMaxAmount();
startAutoScrolling();
}
});
}
public void getScrollMaxAmount()
{
int actualWidth = (horizontalOuterLayout.getMeasuredWidth() - 512);
scrollMax = actualWidth;
}
public void startAutoScrolling()
{
if (scrollTimer == null)
{
scrollTimer = new Timer();
final Runnable Timer_Tick = new Runnable()
{
public void run()
{
moveScrollViewRight();
}
};
if (scrollerSchedule != null)
{
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask()
{
#Override
public void run()
{
runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 30, 30);
}
}
public void moveScrollViewRight()
{
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
if (scrollPos >= scrollMax)
{
scrollPos = 0;
}
horizontalScrollview.scrollTo(scrollPos, 0);
}
/** Adds the images to view. */
public void addImagesToView()
{
for (int i = 0; i < imageNameArray.length; i++)
{
final ImageView imageView = new ImageView(this);
int imageResourceId = getResources().getIdentifier(imageNameArray[i], "drawable", getPackageName());
Drawable image = this.getResources().getDrawable(imageResourceId);
imageView.setBackgroundDrawable(image);
imageView.setTag(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(180, 123);
params.setMargins(0, 25, 0, 25);
imageView.setLayoutParams(params);
horizontalOuterLayout.addView(imageView);
}
}
public void stopAutoScrolling()
{
if (scrollTimer != null)
{
scrollTimer.cancel();
scrollTimer = null;
}
}
public void onBackPressed()
{
super.onBackPressed();
finish();
}
public void onPause()
{
super.onPause();
finish();
}
public void onDestroy()
{
clearTimerTaks(clickSchedule);
clearTimerTaks(scrollerSchedule);
clearTimerTaks(faceAnimationSchedule);
clearTimers(scrollTimer);
clearTimers(faceTimer);
clickSchedule = null;
scrollerSchedule = null;
faceAnimationSchedule = null;
scrollTimer = null;
faceTimer = null;
super.onDestroy();
}
private void clearTimers(Timer timer)
{
if (timer != null)
{
timer.cancel();
timer = null;
}
}
private void clearTimerTaks(TimerTask timerTask)
{
if (timerTask != null)
{
timerTask.cancel();
timerTask = null;
}
}
scrolling back the other way would be easiest.
add in a instance variable that is set to 1.0 (called say scrollDist)
then change this line
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
to
scrollPos = (int) (horizontalScrollview.getScrollX() + scrollDist);
and this line
scrollPos = 0;
to
scrollDist *= -1.0;
this way it will reverse each time it hits the end of the scrollview.
For endless scrolling use the following snnipet
public void getScrollMaxAmount() {
int actualWidth = (horizontalOuterLayout.getMeasuredWidth() - getWindowManager().getDefaultDisplay().getWidth());
scrollMax = actualWidth;
}
public void moveScrollView() {
// ********************* Scrollable Speed ***********************
scrollPos = (int) (horizontalScrollview.getScrollX() + 1.0);
if (scrollPos >= scrollMax) {
Log.v("childCount", ""+scrollMax);
addImagesToView();
getScrollMaxAmount();
}
horizontalScrollview.scrollTo(scrollPos, 0);
}
i have problem with live wallpaper on preview mode.ie the wallpaper image doesn't fit well in landscape mode.it works great on portrait.i need your help.hope you would help me.i have added code
RajawaliRenderer.java
public class RipplesRenderer extends RajawaliRenderer {
private final int NUM_CUBES_H = 4;
private final int NUM_CUBES_V = 4;
private final int NUM_CUBES = NUM_CUBES_H * NUM_CUBES_V;
//private Animation3D[] mAnims;
private TouchRippleFilter mFilter;
private long frameCount;
private final int QUAD_SEGMENTS = 40;
int mScreenHeight,
mScreenWeight;
Gallery_Activity mm;
boolean flag_check = false;
int pos = 0;
int viewBackgroundImageName;
Bitmap texture;
SimpleMaterial planeMat;
int randPosition=1;
int change_value;
int Ripple_number,speed1;
Preferences preferences;
private MediaPlayer myplayer;
private boolean sound;
public RipplesRenderer(Context context) {
super(context);
setFrameRate(50);
this.mContext=context;
randPosition = BitmapUpdate.randomGenerator;
texture = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gthree_one);
//sp=mContext.getSharedPreferences("wallpapersettings",0);
preferences=new Preferences(mContext);
}
protected void initScene() {
if(randPosition!=1) {
texture = BitmapUpdate.bit;
}
mCamera.setPosition(0, 0, -9);
DirectionalLight light = new DirectionalLight(0, 0, 1);
light.setPower(1f);
BaseObject3D group = new BaseObject3D();
DiffuseMaterial material = new DiffuseMaterial();
material.setUseColor(true);
mScreenHeight = GNWallpaper.hieght;
mScreenWeight = GNWallpaper.weight;
Random rnd = new Random();
planeMat = new SimpleMaterial();
Plane plane=new Plane(9,7,1,1);
//Plane plane = new Plane(4, 4, 1, 1);
plane.setRotZ(-90);
plane.setScale(1.0f);
plane.setMaterial(planeMat);
addChild(plane);
mFilter = new TouchRippleFilter();
mPostProcessingRenderer.setQuadSegments(QUAD_SEGMENTS);
mPostProcessingRenderer.setQuality(PostProcessingQuality.MEDIUM);
addPostProcessingFilter(mFilter);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (pos != com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position || randPosition != BitmapUpdate.randomGenerator) {
texture = BitmapUpdate.bit;
pos = com.themebowlapp.galaxynote3livewallpaper.Gallery_Activity.wallpaper_position;
randPosition = BitmapUpdate.randomGenerator;
}
Ripple_number=preferences.getSpeed_controler();
speed1=Ripple_number*100;
super.onSurfaceCreated(gl, config);
}
public void onDrawFrame(GL10 glUnused) {
super.onDrawFrame(glUnused);
mFilter.setTime((float) frameCount++ *.05f);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
super.onSurfaceChanged(gl, width, height);
mFilter.setScreenSize(width, height);
mFilter.setRippleSize((40+speed1));
planeMat.addTexture(mTextureManager.addTexture(texture));
}
public void setTouch(float x, float y) {
mFilter.addTouch(x, y, frameCount *.05f);
}
#Override
public void onTouchEvent(MotionEvent event) {
final int action = event.getAction();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//sound
myplayer = MediaPlayer.create(getContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
myplayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer myplayer) {
myplayer.release();
}
});
setTouch(event.getX() / mScreenWeight, 1.0f - (event.getY() / mScreenHeight));
}
super.onTouchEvent(event);
}
}
Settings.java
public class Settings extends Activity {
public TextView SettingTextObj, BackgroundTextObj;
private RelativeLayout chose_background;
public Preferences preferences;
Context cont = this;
private CheckBox soundcheckbox;
private String PREFRENCES_NAME;
SharedPreferences settings;
// private Button choosebackground;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
chose_background = (RelativeLayout) findViewById(R.id.BackgroundLayoutId);
BackgroundTextObj = (TextView) findViewById(R.id.backgroundTxtViewId);
soundcheckbox = (CheckBox)findViewById(R.id.checkBox1);
settings = getSharedPreferences(PREFRENCES_NAME, 0);
Boolean isChecked = settings.getBoolean("cbx1_ischecked", false);
soundcheckbox.setChecked(isChecked);
soundcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private MediaPlayer myplayer;
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
Editor editor = getSharedPreferences(PREFRENCES_NAME, 0).edit();
editor.putBoolean("cbx1_ischecked", isChecked);
editor.commit();
Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
myplayer = MediaPlayer.create(getBaseContext(), R.raw.water_drop);
myplayer.setVolume(100, 100);
myplayer.start();
}
});
preferences = new Preferences(cont);
chose_background.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String[] items = { "Phone Gallery", "Choose Background" };
AlertDialog.Builder builder = new AlertDialog.Builder(
Settings.this);
builder.setTitle("Pick a Background");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
startActivity(new Intent(Settings.this, PhoneGallery_Activity.class));
} else {
startActivity(new Intent(Settings.this, Gallery_Activity.class));
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
}
GNWallpaper.java
public class GNWallpaper extends Wallpaper {
private RipplesRenderer mRenderer;
private String imageBg;
private int cvwidth;
private int cvheight;
private int visibleWidth;
private Bitmap bg;
private String LoadText;
private boolean sound;
private MediaPlayer myplayer;
public static WindowManager display;
static int height,width;
//private Integer[] mImageIds = { R.drawable.gthree_one,R.drawable.gthree_two,R.drawable.gthree_three, R.drawable.gthree_four, R.drawable.gthree_five, R.drawable.gthree_six,};
private int position;
public Engine onCreateEngine() {
display =(WindowManager) getSystemService(Context.WINDOW_SERVICE);
height= display.getDefaultDisplay().getHeight();
width= display.getDefaultDisplay().getWidth();
mRenderer = new RipplesRenderer(this);
//Log.i("shibbu"," hello");
return new WallpaperEngine(this.getSharedPreferences(SHARED_PREFS_NAME,
Context.MODE_PRIVATE), getBaseContext(), mRenderer, false);
}
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
imageBg = prefs.getString("image_custom", "Bad Image");
getBackground();
sound=prefs.getBoolean("pref_sound", false);
// //sound
// sound=prefs.getBoolean("pref_sound", false);
}
void getBackground() {
if (this.cvwidth == 0 || this.cvheight == 0 || this.visibleWidth == 0) {
this.cvwidth = 1290;
this.cvheight = 800;
this.visibleWidth = 1290;
}
if(new File(imageBg).exists()) {
int SampleSize = 1;
do {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bg = BitmapFactory.decodeFile(imageBg, options);
SampleSize = (int) (Math.ceil(options.outWidth/(this.visibleWidth * 2))*2);
options.inJustDecodeBounds = false;
try {
options.inSampleSize = SampleSize;
bg = BitmapFactory.decodeFile(imageBg, options);
} catch (OutOfMemoryError e) {
SampleSize = SampleSize * 2;
}
} while (bg == null);
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
} else {
bg = BitmapFactory.decodeResource(getResources(), R.drawable.gthree_one);
//bg = BitmapFactory.decodeResource(getResources(), mImageIds[position]);
//position++;
bg = Bitmap.createScaledBitmap(bg, this.cvwidth/2, this.cvheight, true);
LoadText = "";
}
}
}
Refer this link.It will help you to change to landscape view..
http://tips4android.blogspot.in/2012/01/android-tips-how-to-get-screen.html
I am using view pager indicator and i have sucessfully implemented it but My problem is that my swipe is very slow.Any help regarding this will be appreciated.
My indicator activity:
public class ViewPagerIndicatorActivity extends FragmentActivity {
static PagerAdapter mPagerAdapter;
static ViewPager mViewPager;
static ViewPagerIndicator mIndicator;
static int position,position1;
static String PositionTitle;
static String addposition;
ProgressDialog dialog;
public Context _context=this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our custom adapter to supply pages to the viewpager.
try{
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
// Start at a custom position
RelativeLayout firsthead=(RelativeLayout)findViewById(R.id.firsthead);
firsthead.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ii=new Intent(getApplicationContext(),WebviewNew.class);
startActivity(ii);
}
});
mViewPager.setCurrentItem(0);
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
mViewPager.setOnPageChangeListener(mIndicator);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
mViewPager.setAdapter(null);
super.onDestroy();
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
#Override
public void onCurrentClicked(View v) {
Toast.makeText(ViewPagerIndicatorActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onNextClicked(View v) {
mViewPager.setCurrentItem(Math.min(mPagerAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
#Override
public void onPreviousClicked(View v) {
mViewPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
class PagerAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
Fragment f = new Fragment();
if(pos==0)
{
f=LayoutOne.newInstance(_context);
}
if(pos==1)
{
f=LayoutTwo.newInstance(_context);
}
if(pos==2)
{
f=Layoutthree.newInstance(_context);
}
if(pos==3)
{
f=Layoutfour.newInstance(_context);
}
return f;
}
#Override
public int getCount() {
return list2.length;
}
#Override
public String getTitle(int pos){
PositionTitle=list2[pos];
return PositionTitle;
}
}
public static class ItemFragment extends ListFragment{
String[] l1;
static ItemFragment newInstance1(String[] date) {
ItemFragment f = new ItemFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putStringArray("date", date);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.l1=list2;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.date_fragment, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public static final String[] list2 = new String[]{"Catagories","Latest","Most Downloaded","Top Rated"};
private class StartTaskP extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(ViewPagerIndicatorActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String hello = null;
try
{} catch (Exception e)
{
e.printStackTrace();
}
return hello;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
mIndicator.init(0, mPagerAdapter.getCount(), mPagerAdapter);
Resources res = getResources();
System.out.println("test11");
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{78, 103, 0});
mIndicator.setUnfocusedTextColor(new int[]{255,255,255});
//mIndicator.setFocusedTextColor(R.drawable.navigationtextcurrent);
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
dialog.dismiss();
}
}
and my ViewPagerIndicator:
public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener {
private static final int PADDING = 10;
int i=0;
TextView mPrevious;
TextView mCurrent;
TextView mNext;
static int mCurItem;
int mRestoreCurItem = -1;
Intent ii= new Intent();
Context mContext;
static int PresentPosition1;
static String textCarrier;
LinearLayout mPreviousGroup;
LinearLayout mNextGroup;
int mArrowPadding;
int mSize;
ImageView mCurrentIndicator;
ImageView mPrevArrow;
ImageView mNextArrow;
static PageInfoProvider mPageInfoProvider;
int[] mFocusedTextColor;
int[] mUnfocusedTextColor;
OnClickListener mOnClickHandler;
public interface PageInfoProvider{
String getTitle(int pos);
}
public interface OnClickListener{
void onNextClicked(View v);
void onPreviousClicked(View v);
void onCurrentClicked(View v);
}
public void setOnClickListener(OnClickListener handler){
this.mOnClickHandler = handler;
mPreviousGroup.setOnClickListener(new OnPreviousClickedListener());
mCurrent.setOnClickListener(new OnCurrentClickedListener());
mNextGroup.setOnClickListener(new OnNextClickedListener());
}
public int getCurrentPosition(){
return mCurItem;
}
public void setPageInfoProvider(PageInfoProvider pageInfoProvider){
this.mPageInfoProvider = pageInfoProvider;
}
public void setFocusedTextColor(int[] col){
System.arraycopy(col, 0, mFocusedTextColor, 0, 3);
updateColor(0);
}
public void setUnfocusedTextColor(int[] col){
System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3);
mNext.setTextColor(Color.argb(160, col[0], col[1], col[2]));
mPrevious.setTextColor(Color.argb(160, col[0], col[1], col[2]));
updateColor(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
Bundle b = new Bundle();
b.putInt("current", this.mCurItem);
b.putParcelable("viewstate", state);
return b;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(((Bundle)state).getParcelable("viewstate"));
mCurItem = ((Bundle)state).getInt("current", mCurItem);
this.setText(mCurItem - 1);
this.updateArrows(mCurItem);
this.invalidate();
}
/**
* Initialization
*
* #param startPos The initially selected element in the ViewPager
* #param size Total amount of elements in the ViewPager
* #param pageInfoProvider Interface that returns page titles
*/
public void init(int startPos, int size, PageInfoProvider pageInfoProvider){
setPageInfoProvider(pageInfoProvider);
this.mSize = size;
setText(startPos - 1);
mCurItem = startPos;
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
addContent();
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
addContent();
}
public ViewPagerIndicator(Context context) {
super(context);
addContent();
}
/**
* Add drawables for arrows
*
* #param prev Left pointing arrow
* #param next Right pointing arrow
*/
public void setArrows(Drawable prev, Drawable next){
this.mPrevArrow = new ImageView(getContext());
//this.mPrevArrow.setImageDrawable(prev);
this.mPrevArrow.setVisibility(View.INVISIBLE);
this.mNextArrow = new ImageView(getContext());
//this.mNextArrow.setImageDrawable(next);
LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//arrowLayoutParams.gravity = Gravity.CENTER;
mPreviousGroup.removeAllViews();
mPreviousGroup.addView(mPrevArrow, arrowLayoutParams);
mPreviousGroup.addView(mPrevious, arrowLayoutParams);
mPrevious.setPadding(PADDING, 0, 0, 0);
mNext.setPadding(0, 0, PADDING, 0);
mArrowPadding = PADDING + prev.getIntrinsicWidth();
mNextGroup.addView(mNextArrow, arrowLayoutParams);
updateArrows(mCurItem);
}
/**
* Create all views, build the layout
*/
private void addContent(){
mFocusedTextColor = new int[]{244, 240, 211};
mUnfocusedTextColor = new int[]{160,131,21};
// Text views
// set font
mPrevious = new TextView(getContext());
mCurrent = new TextView(getContext());
mNext = new TextView(getContext());
RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
previousParams.addRule(RelativeLayout.ALIGN_LEFT);
previousParams.leftMargin=-28;
previousParams.topMargin=10;
RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
currentParams.topMargin=10;
RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
nextParams.rightMargin=-40;
nextParams.topMargin=10;
// Groups holding text and arrows
mPreviousGroup = new LinearLayout(getContext());
mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL);
mNextGroup = new LinearLayout(getContext());
mNextGroup.setOrientation(LinearLayout.HORIZONTAL);
mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mPreviousGroup, previousParams);
addView(mCurrent, currentParams);
addView(mNextGroup, nextParams);
mPrevious.setSingleLine();
mCurrent.setSingleLine();
mNext.setSingleLine();
mPrevious.setText("previous");
mCurrent.setText("current");
mNext.setText("next");
try{
Typeface tf=Typeface.createFromAsset(getContext().getAssets(), "fonts/trebuc.otf");
mPrevious.setTypeface(tf);
mCurrent.setTypeface(tf);
mNext.setTypeface(tf);
}catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
mPrevious.setClickable(false);
mNext.setClickable(false);
mCurrent.setClickable(true);
mPreviousGroup.setClickable(true);
mNextGroup.setClickable(true);
// Set colors
mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
updateColor(0);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
positionOffsetPixels = adjustOffset(positionOffsetPixels);
position = updatePosition(position, positionOffsetPixels);
setText(position - 1);
/*System.out.println("PageScrolled:"+(position-1));
System.out.println("PageScrollednew:"+PresentPosition);
*/updateColor(positionOffsetPixels-1);
updateArrows(position);
//updatePositions(positionOffsetPixels);
updatePositions(position);
mCurItem = position;
Bundle ii=new Bundle();
//ii.putExtra("mcurItem", mCurItem);
ii.putInt("key", mCurItem);
}
void updatePositions(int positionOffsetPixels){
int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight();
int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding;
if(positionOffsetPixels > 0){
maxOffset %= this.getPaddingLeft();
int offset = Math.min(positionOffsetPixels, maxOffset);
mCurrent.setPadding(0, 0, 2 * offset, 0);
}else{
maxOffset -= this.getPaddingRight();
int offset = Math.max(positionOffsetPixels, -maxOffset);
mCurrent.setPadding(-2 * offset, 0, 0, 0);
}
}
void updateArrows(int position){
if(mPrevArrow != null){
mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE);
mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE);
}
}
int updatePosition(int givenPosition, int offset){
int pos;
if(offset < 0){
pos = givenPosition + 1;
}else{
pos = givenPosition;
}
return pos;
}
/**
* Fade "currently showing" color depending on it's position
*
* #param offset
*/
void updateColor(int offset){
offset = Math.abs(offset);
// Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN
int width = this.getWidth();
float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f);
fraction = Math.min(1, fraction);
int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction));
int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction));
int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction));
mCurrent.setTextColor(Color.argb(255, r, g, b));
}
/**
* Update text depending on it's position
*
* #param prevPos
*/
void setText(int prevPos){
PresentPosition1=prevPos;
if(prevPos < 0){
mPrevious.setText("");
}else{
mPrevious.setText(mPageInfoProvider.getTitle(prevPos));
}
mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1));
PresentPosition1=prevPos;
//System.out.println("present text"+mPageInfoProvider.getTitle(prevPos + 1));
if(prevPos + 2 == this.mSize){
mNext.setText("");
}else{
mNext.setText(mPageInfoProvider.getTitle(prevPos + 2));
}
}
// Original:
// 244, 245, 0, 1, 2
// New:
// -2, -1, 0, 1, 2
int adjustOffset(int positionOffsetPixels){
// Move offset half width
positionOffsetPixels += this.getWidth() / 2;
// Clamp to width
positionOffsetPixels %= this.getWidth();
// Center around zero
positionOffsetPixels -= this.getWidth() / 2;
return positionOffsetPixels;
}
#Override
public void onPageSelected(int position) {
// Reset padding when the page is finally selected (May not be necessary)
mCurrent.setPadding(0, 0, 0, 0);
}
class OnPreviousClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this);
}
}
}
class OnCurrentClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this);
}
}
}
class OnNextClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onNextClicked(ViewPagerIndicator.this);
}
}
}
}