Unity Interactable = False suddenly not working - button

now i encountered a very very weird issue. below is the code. pardon the length. This class has multiple function that were working when there only 3 (upt to button C)buttons being reference, in fact the one installed on my phone has the already pressed button disabled after i go back to the initial scene.
So me thinking all is good decided to do this for all the buttons that I have on my initial Screen. But for some reason it is not working, it is not disabling the buttons anymore. I have the GameLogic.cs where i have my variables declared and this script as well. 16 buttons = 16 Alphabets. So basically it just increments a value once button is pressed then once we go back to the initial screen On update, if the value is >= 1 then that particular button must be disabled.
Again it is working when i first built it for the phone. it is there. this is so weird. Maybe you can see some issue with the code here perhaps?
Thanks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class forButtonDisabler : MonoBehaviour {
public Button buttonA;
public Button buttonB;
public Button buttonC;
public Button buttonD;
public Button buttonE;
public Button buttonF;
public Button buttonG;
public Button buttonH;
public Button buttonI;
public Button buttonJ;
public Button buttonK;
public Button buttonL;
public Button buttonM;
public Button buttonN;
public Button buttonO;
public Button buttonP;
void OnEnable()
{
//Register Button Events
buttonA = GameObject.Find("btn5ptsPP").GetComponent<Button>();
buttonB = GameObject.Find("btn5ptsDP").GetComponent<Button>();
buttonC = GameObject.Find("btn5ptsTE").GetComponent<Button>();
buttonD = GameObject.Find("btn5ptsTA").GetComponent<Button>();
buttonE= GameObject.Find("btn10ptsPP").GetComponent<Button>();
buttonF = GameObject.Find("btn10ptsDP").GetComponent<Button>();
buttonG = GameObject.Find("btn10ptsTE").GetComponent<Button>();
buttonH = GameObject.Find("btn10ptsTA").GetComponent<Button>();
buttonI = GameObject.Find("btn15ptsPP").GetComponent<Button>();
buttonJ = GameObject.Find("btn15ptsDP").GetComponent<Button>();
buttonK = GameObject.Find("btn15ptsTE").GetComponent<Button>();
buttonL = GameObject.Find("btn15ptsTA").GetComponent<Button>();
buttonM = GameObject.Find("btn20ptsPP").GetComponent<Button>();
buttonN = GameObject.Find("btn20ptsDP").GetComponent<Button>();
buttonO = GameObject.Find("btn20ptsTE").GetComponent<Button>();
buttonP = GameObject.Find("btn20ptsTA").GetComponent<Button>();
buttonA.onClick.AddListener(() => buttonCallBack(buttonA));
buttonB.onClick.AddListener(() => buttonCallBack(buttonB));
buttonC.onClick.AddListener(() => buttonCallBack(buttonC));
buttonD.onClick.AddListener(() => buttonCallBack(buttonD));
buttonE.onClick.AddListener(() => buttonCallBack(buttonE));
buttonF.onClick.AddListener(() => buttonCallBack(buttonF));
buttonG.onClick.AddListener(() => buttonCallBack(buttonG));
buttonH.onClick.AddListener(() => buttonCallBack(buttonH));
buttonI.onClick.AddListener(() => buttonCallBack(buttonI));
buttonJ.onClick.AddListener(() => buttonCallBack(buttonJ));
buttonK.onClick.AddListener(() => buttonCallBack(buttonK));
buttonL.onClick.AddListener(() => buttonCallBack(buttonL));
buttonM.onClick.AddListener(() => buttonCallBack(buttonM));
buttonN.onClick.AddListener(() => buttonCallBack(buttonN));
buttonO.onClick.AddListener(() => buttonCallBack(buttonO));
buttonP.onClick.AddListener(() => buttonCallBack(buttonP));
}
private void buttonCallBack(Button buttonPressed)
{
if (buttonPressed == buttonA)
{
GameLogic.Cbtn1++;
}
if (buttonPressed == buttonB)
{
GameLogic.Cbtn2++;
}
if (buttonPressed == buttonC)
{
GameLogic.Cbtn3++;
}
if (buttonPressed == buttonD)
{
GameLogic.Cbtn4++;
}
if (buttonPressed == buttonE)
{
GameLogic.Cbtn5++;
}
if (buttonPressed == buttonF)
{
GameLogic.Cbtn6++;
}
if (buttonPressed == buttonG)
{
GameLogic.Cbtn7++;
}
if (buttonPressed == buttonH)
{
GameLogic.Cbtn8++;
}
if (buttonPressed == buttonI)
{
GameLogic.Cbtn9++;
}
if (buttonPressed == buttonJ)
{
GameLogic.Cbtn10++;
}
if (buttonPressed == buttonK)
{
GameLogic.Cbtn11++;
}
if (buttonPressed == buttonL)
{
GameLogic.Cbtn12++;
}
if (buttonPressed == buttonM)
{
GameLogic.Cbtn13++;
}
if (buttonPressed == buttonN)
{
GameLogic.Cbtn14++;
}
if (buttonPressed == buttonO)
{
GameLogic.Cbtn15++;
}
if (buttonPressed == buttonP)
{
GameLogic.Cbtn16++;
}
}
void OnDisable()
{
//Un-Register Button Events
buttonA.onClick.RemoveAllListeners();
buttonB.onClick.RemoveAllListeners();
buttonC.onClick.RemoveAllListeners();
buttonD.onClick.RemoveAllListeners();
buttonE.onClick.RemoveAllListeners();
buttonF.onClick.RemoveAllListeners();
buttonG.onClick.RemoveAllListeners();
buttonH.onClick.RemoveAllListeners();
buttonI.onClick.RemoveAllListeners();
buttonJ.onClick.RemoveAllListeners();
buttonK.onClick.RemoveAllListeners();
buttonL.onClick.RemoveAllListeners();
buttonM.onClick.RemoveAllListeners();
buttonN.onClick.RemoveAllListeners();
buttonO.onClick.RemoveAllListeners();
buttonP.onClick.RemoveAllListeners();
}
// Update is called once per frame
void Update()
{
if (GameLogic.Cbtn1 >= 1)
{
buttonA.interactable = false;
}
if (GameLogic.Cbtn2 >= 1)
{
buttonB.interactable = false;
}
if (GameLogic.Cbtn3 >= 1)
{
buttonC.interactable = false;
}
if (GameLogic.Cbtn4 >= 1)
{
buttonD.interactable = false;
}
if (GameLogic.Cbtn5 >= 1)
{
buttonE.interactable = false;
}
if (GameLogic.Cbtn6 >= 1)
{
buttonF.interactable = false;
}
if (GameLogic.Cbtn7 >= 1)
{
buttonG.interactable = false;
}
if (GameLogic.Cbtn8 >= 1)
{
buttonH.interactable = false;
}
if (GameLogic.Cbtn9 >= 1)
{
buttonI.interactable = false;
}
if (GameLogic.Cbtn10 >= 1)
{
buttonJ.interactable = false;
}
if (GameLogic.Cbtn11 >= 1)
{
buttonK.interactable = false;
}
if (GameLogic.Cbtn12 >= 1)
{
buttonL.interactable = false;
}
if (GameLogic.Cbtn13 >= 1)
{
buttonM.interactable = false;
}
if (GameLogic.Cbtn14 >= 1)
{
buttonN.interactable = false;
}
if (GameLogic.Cbtn15 >= 1)
{
buttonO.interactable = false;
}
if (GameLogic.Cbtn16 >= 1)
{
buttonP.interactable = false;
}
}
}

Related

Secondary Toolbar items not fitting the screen

I have a Xamarin.Forms app with FreshMvvm, and I use secondary ToolbarItems. To do it in iOS, I had to make a custom renderer (unlike in Android). I was given a solution on how to implement it here:
ToolbarItems do not look right in iOS
This solution works perfectly for me. But by now, the toolbar menu grew longer, and some of its elements do not fit the iPhone's screen. I can slide the menu and see all the elements, but as soon as I release the screen, the view jumps back up, and while it is held by a finger, the elements are not clickable. How can this be solved? Can the menu made to wrap, or something else?
On Android, the menu stays where I scroll and I can click every item. Can it made stay where scrolled on iOS, too?
Here is my renderer's code:
using CoreGraphics;
using MobileApp.iOS.Renderers;
using MobileApp.iOS.Services;
using MobileApp.Pages;
using MobileApp.Services;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomToolbarContentPage),
typeof(RightToolbarMenuCustomRenderer))]
namespace MobileApp.iOS.Renderers
{
class RightToolbarMenuCustomRenderer : PageRenderer
{
private List<ToolbarItem> _primaryItems;
private List<ToolbarItem> _secondaryItems;
private UITableView _table;
private UITapGestureRecognizer _tapGestureRecognizer;
private UIView _transparentView;
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
if (e.NewElement is IAddToolbarItem item)
{
item.ToolbarItemAdded += Item_ToolbarItemAdded;
}
base.OnElementChanged(e);
}
private void Item_ToolbarItemAdded(object sender, System.EventArgs e)
{
if (Element is ContentPage page)
{
_primaryItems = page.ToolbarItems.Where(i => i.Order == ToolbarItemOrder.Primary).ToList();
_secondaryItems = page.ToolbarItems.Where(i => i.Order == ToolbarItemOrder.Secondary).ToList();
_secondaryItems.ForEach(t => page.ToolbarItems.Remove(t));
}
var element = (ContentPage)Element;
if (_secondaryItems?.Count == 0 && element.ToolbarItems.Any(a => (a.IconImageSource as FileImageSource)?.File == "more.png"))
{
element.ToolbarItems.Clear();
}
else if (_secondaryItems?.Count >= 1 && !element.ToolbarItems.Any(a => (a.IconImageSource as FileImageSource)?.File == "more.png"))
{
element.ToolbarItems.Add(new ToolbarItem()
{
Order = ToolbarItemOrder.Primary,
IconImageSource = "more.png",
Priority = 1,
Command = new Command(ToggleDropDownMenuVisibility)
});
}
}
private void ToggleDropDownMenuVisibility()
{
if (!DoesTableExist())
{
if ((View?.Subviews != null)
&& (View.Subviews.Length > 0)
&& (View.Bounds != null)
&& (_secondaryItems != null)
&& (_secondaryItems.Count > 0))
{
_table = OpenDropDownMenu(Element as IAddToolbarItem);
Add(_table);
}
}
else
CloseDropDownMenu();
}
private bool DoesTableExist()
{
if (View?.Subviews != null)
{
foreach (var subview in View.Subviews)
{
if (_table != null && subview == _table)
{
return true;
}
}
}
if (_tapGestureRecognizer != null)
{
_transparentView?.RemoveGestureRecognizer(_tapGestureRecognizer);
_tapGestureRecognizer = null;
}
_table = null;
_tapGestureRecognizer = null;
return false;
}
private UITableView OpenDropDownMenu(IAddToolbarItem secondaryMenuSupport)
{
_transparentView = _transparentView = new UIView(new CGRect(0, 0, View.Bounds.Width, View.Bounds.Height))
{
BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0)
};
_tapGestureRecognizer = new UITapGestureRecognizer(CloseDropDownMenu);
_transparentView.AddGestureRecognizer(_tapGestureRecognizer);
Add(_transparentView);
UITableView table = null;
if (_secondaryItems != null && _secondaryItems.Count > 0)
{
table = new UITableView(GetPositionForDropDownMenu(secondaryMenuSupport.RowHeight, secondaryMenuSupport.TableWidth))
{
Source = new TableSource(_secondaryItems, _transparentView),
ClipsToBounds = false
};
table.ScrollEnabled = true;
table.Layer.ShadowColor = secondaryMenuSupport.ShadowColor.ToCGColor();
table.Layer.ShadowOpacity = secondaryMenuSupport.ShadowOpacity;
table.Layer.ShadowRadius = secondaryMenuSupport.ShadowRadius;
table.Layer.ShadowOffset = new SizeF(secondaryMenuSupport.ShadowOffsetDimension, secondaryMenuSupport.ShadowOffsetDimension);
table.BackgroundColor = secondaryMenuSupport.MenuBackgroundColor.ToUIColor();
}
return table;
}
public override void ViewWillDisappear(bool animated)
{
CloseDropDownMenu();
base.ViewWillDisappear(animated);
}
private RectangleF GetPositionForDropDownMenu(float rowHeight, float tableWidth)
{
if ((View?.Bounds != null)
&& (_secondaryItems != null)
&& (_secondaryItems.Count > 0))
{
return new RectangleF(
(float)View.Bounds.Width - tableWidth,
0,
tableWidth,
_secondaryItems.Count() * rowHeight);
}
else
{
return new RectangleF(0.0f, 0.0f, 0.0f, 0.0f);
}
}
private void CloseDropDownMenu()
{
if (_table != null)
{
if (_tapGestureRecognizer != null)
{
_transparentView?.RemoveGestureRecognizer(_tapGestureRecognizer);
_tapGestureRecognizer = null;
}
if (View?.Subviews != null)
{
foreach (var subview in View.Subviews)
{
if (subview == _table)
{
_table.RemoveFromSuperview();
break;
}
}
if (_transparentView != null)
{
foreach (var subview in View.Subviews)
{
if (subview == _transparentView)
{
_transparentView.RemoveFromSuperview();
break;
}
}
}
}
_table = null;
_transparentView = null;
}
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
if (_table != null)
{
if (Element is IAddToolbarItem secondaryMenuSupport)
PositionExistingDropDownMenu(secondaryMenuSupport.RowHeight, secondaryMenuSupport.TableWidth);
}
}
private void PositionExistingDropDownMenu(float rowHeight, float tableWidth)
{
if ((View?.Bounds != null)
&& (_secondaryItems != null)
&& (_secondaryItems.Count > 0)
&& (_table != null))
{
_table.Frame = GetPositionForDropDownMenu(rowHeight, tableWidth);
}
}
}
}
ADDITION:
public class TableSource : UITableViewSource
{
List<ToolbarItem> _tableItems;
string[] _tableItemTexts;
string CellIdentifier = "TableCell";
UIView _tableSuperView = null;
public TableSource(List<ToolbarItem> items, UIView tableSuperView)
{
_tableItems = items;
_tableSuperView = tableSuperView;
_tableItemTexts = items.Select(a => a.Text).ToArray();
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return _tableItemTexts?.Length ?? 0;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
string item = _tableItemTexts[indexPath.Row];
if (cell == null)
{ cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); }
cell.TextLabel.Text = item;
return cell;
}
public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
{
return 56;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
var command = _tableItems[indexPath.Row].Command;
command.Execute(_tableItems[indexPath.Row].CommandParameter);
tableView.DeselectRow(indexPath, true);
tableView.RemoveFromSuperview();
if (_tableSuperView != null)
{
_tableSuperView.RemoveFromSuperview();
}
}
}
public interface IAddToolbarItem
{
event EventHandler ToolbarItemAdded;
Color CellBackgroundColor { get; }
Color CellTextColor { get; }
Color MenuBackgroundColor { get; }
float RowHeight { get; }
Color ShadowColor { get; }
float ShadowOpacity { get; }
float ShadowRadius { get; }
float ShadowOffsetDimension { get; }
float TableWidth { get; }
}
Here you can download the project that reproduces the issue:
https://github.com/DavidShochet/Public
Well, I still can't reproduce the problem with your updated code. I don't if it is a solution and I just want to clarify my comment here.
In your code, you add the _table to the View:
_table = OpenDropDownMenu(Element as IAddToolbarItem);
Add(_table);
What I want you to have a try is add the _table to _transparentView :
_table = OpenDropDownMenu(Element as IAddToolbarItem);
//Add(_table);
_transparentView.Add(_table);
It would be better if you can provide us a Minimal, Reproducible Example so that I can debug it on my side.
Update:
I found the problem is here, you set the height of table _secondaryItems.Count() * rowHeight) which is longer then the view when the toolbar menu grew longer:
private RectangleF GetPositionForDropDownMenu(float rowHeight, float tableWidth)
{
if ((View?.Bounds != null)
&& (_secondaryItems != null)
&& (_secondaryItems.Count > 0))
{
return new RectangleF(
(float)View.Bounds.Width - tableWidth,
0,
tableWidth,
//here is the cause
_secondaryItems.Count() * rowHeight);
}
else
{
return new RectangleF(0.0f, 0.0f, 0.0f, 0.0f);
}
}
Solution: change the height of tablview to (float)View.Bounds.Height:
private RectangleF GetPositionForDropDownMenu(float rowHeight, float tableWidth)
{
if ((View?.Bounds != null)
&& (_secondaryItems != null)
&& (_secondaryItems.Count > 0))
{
return new RectangleF(
(float)View.Bounds.Width - tableWidth,
0,
tableWidth,
(float)View.Bounds.Height);
}
else
{
return new RectangleF(0.0f, 0.0f, 0.0f, 0.0f);
}
}

Xamarin forms: Auto scrolling for CarouselPage children

I have 4 children (page1,page2,page3, and page4) in a CarouselPage, I need to auto-scroll the children in every 3 seconds. Initially, page1 is showing on the UI, then page2 -> page3 -> page 4 again starting from page1.
I have done like below for this feature using OnCurrentPageChanged() and await Task.Delay(TimeSpan.FromSeconds(3));:
protected async override void OnCurrentPageChanged()
{
base.OnCurrentPageChanged();
await Task.Delay(TimeSpan.FromSeconds(3));
int index = Children.IndexOf(CurrentPage);
if (index == 0)
{
CurrentPage = Children[1];
}
else if (index == 1)
{
CurrentPage = Children[2];
}
else if (index == 2)
{
CurrentPage = Children[3];
}
else if (index == 3)
{
CurrentPage = Children[0];
}
}
The auto-scroll is successful by this approach.
But if I manually scroll the page in between the auto-scroll, then the time delay is reducing. Suddenly(less than 3 sec) the next page is showing on the screen. If I manually swipe the page I need to wait on the page for 3 seconds. How can I solve this issue?
There is a Exciting Library CardsView please look into it.
it will not only solve your problem but your apps looks cool as well.
here is Source Project , https://github.com/AndreiMisiukevich/CardView .
check CarouselSampleXamlView in that, SlideShowDuration property for carousel which handles all stuff.
Hope it helps.
Please do not put the transfer page to the OnCurrentPageChanged method.
You can put it in your Page's constructor.
public partial class MainPage : CarouselPage
{
bool isStart = true;
public MainPage()
{
InitializeComponent();
Device.StartTimer(new TimeSpan(0, 0, 3), () =>
{
Device.BeginInvokeOnMainThread(() =>
{
int index = Children.IndexOf(CurrentPage);
if (index == 0)
{
CurrentPage = Children[1];
isStart = true;
}
else if (index == 1)
{
CurrentPage = Children[2];
isStart = true;
}
else if (index == 2)
{
CurrentPage = Children[3];
isStart = true;
}
else if (index == 3)
{
CurrentPage = Children[0];
isStart = true;
}
});
return isStart; // runs again, or false to stop
});
}
}
If you change the page by swipe, the time delay is not reducing.
However, If you want to wait on the page for 3 seconds after swiping. You have to use custom renderer to achieve it. You should monitor the viewpager's onTouchEventin android(but I cannot found a solution in IOS). This way will have caton, so above way will be better.
[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace CarouselPageDemo.Droid
{
public class CustomCarouselPageRenderer: CarouselPageRenderer
{
public CustomCarouselPageRenderer(Context context) : base(context) {
}
protected override void OnElementChanged(ElementChangedEventArgs<CarouselPage> e)
{
base.OnElementChanged(e);
if (this.ChildCount > 0 && this.GetChildAt(0) is ViewPager viewPager)
{
viewPager.Touch -= ViewPagerTouched;
viewPager.Touch += ViewPagerTouched;
}
}
private void ViewPagerTouched(object sender, TouchEventArgs e)
{
MessagingCenter.Send<App, string>(App.Current as App, "OpenPage", "stop");
}
}
}
CarouselPage_CurrentPageChanged method
private async void CarouselPage_CurrentPageChanged(object sender, EventArgs e)
{
var tokenSource = new CancellationTokenSource();
await Task.Delay(TimeSpan.FromSeconds(3), tokenSource.Token);
MessagingCenter.Subscribe<App, string>(App.Current, "OpenPage", (snd, arg) =>
{
tokenSource.Cancel();
});
int index = Children.IndexOf(CurrentPage);
if (index == 0)
{
CurrentPage = Children[1];
}
else if (index == 1)
{
CurrentPage = Children[2];
}
else if (index == 2)
{
CurrentPage = Children[3];
}
else if (index == 3)
{
CurrentPage = Children[0];
}
}

AutoComplete javaFx ComboBox items not showing after "clearing selection"

I'm trying to make an autocomplete combobox in javafx and im almost done but every time i try to submit and clear selection so the user can choose another choice , all the items get hidden except the one he chose last time
// this the class that i used turn a normal combobox to an autocomplete one
public class AutoCompleteComboBoxListener<T> implements EventHandler<KeyEvent> {
private ComboBox<T> comboBox;
private ObservableList<T> data;
private boolean moveCaretToPos = false;
private int caretPos;
public AutoCompleteComboBoxListener(final ComboBox<T> comboBox) {
this.comboBox = comboBox;
data = comboBox.getItems();
this.comboBox.setEditable(true);
this.comboBox.setOnKeyReleased(AutoCompleteComboBoxListener.this);
this.showOnFocus();
}
#Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.UP) {
caretPos = -1;
moveCaret(comboBox.getEditor().getText().length());
return;
} else if(event.getCode() == KeyCode.DOWN) {
if(!comboBox.isShowing())
comboBox.show();
caretPos = -1;
moveCaret(comboBox.getEditor().getText().length());
return;
}
if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT
|| event.isControlDown() || event.getCode() == KeyCode.HOME
|| event.getCode() == KeyCode.END || event.getCode() == KeyCode.TAB) {
return;
}
System.out.println(caretPos);
comboBox.hide();
if(event.getCode() == KeyCode.BACK_SPACE) {
moveCaretToPos = true;
caretPos = comboBox.getEditor().getCaretPosition();
} else if(event.getCode() == KeyCode.DELETE) {
moveCaretToPos = true;
caretPos = comboBox.getEditor().getCaretPosition();
}
ObservableList<T> list = FXCollections.observableArrayList();
for (int i=0; i<data.size(); i++) {
if(data.get(i).toString().toLowerCase().startsWith(
AutoCompleteComboBoxListener.this.comboBox
.getEditor().getText().toLowerCase())) {
list.add(data.get(i));
}
}
String t = comboBox.getEditor().getText();
comboBox.setItems(list);
comboBox.getEditor().setText(t);
if(!moveCaretToPos) {
caretPos = -1;
}
moveCaret(t.length());
if(!list.isEmpty()) {
comboBox.show();
String editorText;
editorText=comboBox.getEditor().getText();
list.sort((a, b) -> Integer.compare(a.toString().length(), b.toString().length()));
comboBox.getSelectionModel().selectFirst();
comboBox.getEditor().setText(editorText);
moveCaret(comboBox.getSelectionModel().getSelectedItem().toString().length());
}
if (event.getCode()==KeyCode.ENTER){
comboBox.hide();
comboBox.getEditor().setText(comboBox.getSelectionModel().getSelectedItem().toString());
}
}
private void moveCaret(int textLength) {
if(caretPos == -1)
comboBox.getEditor().positionCaret(textLength);
else
comboBox.getEditor().positionCaret(caretPos);
moveCaretToPos = false;
}
public void showOnFocus(){
this.comboBox.focusedProperty().addListener((obs, oldVal, newVal) ->
this.comboBox.show());
}
}
// and this is what the submit button does the the comboboxes
button.setOnAction(e-> {
combo1.getSelectionModel().clearSelection();
combo1.getSelectionModel().clearSelection();
});

refresh adapter with recyclerview using D-pad holding focus

I am stuck on a complex situation, when I am refreshing my adapter of recyclerview by notifyDataSetChanged, while it having focus on particular cell (with D-PAD), is being loss. After refresh focus is not showing
private void refreshedData() {
flag1 = true;
// new MyAsycTas().execute();
focusedElement();
// select();
runnable = new Runnable() {
#Override
public void run() {
Log.e(TAG, "Data refreshed starrt.......");
// isRefreshedData = true;
fetchXmlFromUrl = new FetchDataFromUrl(Demo2Activity.this, 0, Demo2Activity.this);
handler.removeCallbacks(runnable);
select();
handler.postDelayed(runnable, 9000);
}
};
// handler.postDelayed(runnable,
// Integer.valueOf(MyStaticClass.refreshTime) * 60000);
handler.postDelayed(runnable, 9000);
}
...
public void select() {
if (verticalListView != null) {
View view = verticalListView.getChildAt(vertical_position);
if (view != null) {
view = verticalListView.getChildAt(vertical_position);
recyclerView = (RecyclerView) view.findViewById(R.id.horizontal_recyclerview);
if (recyclerView != null) {
verticalListView.scrollToPosition(vertical_position);
((View) recyclerView.getChildAt(horizontal_position)).findViewById(R.id.cat_button_thumabnail)
.requestFocus();
} else {
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.home_fragment_menu_container);
linearLayout.getChildAt(horizontal_position).requestFocus();
}
}
}
// refreshedData();
}
..
public void focusedElement() {
if (verticalListView != null) {
View view = verticalListView.getLayoutManager().getFocusedChild();
if (view != null) {
recyclerView = (RecyclerView) view.findViewById(R.id.horizontal_recyclerview);
if (recyclerView != null) {
vertical_position = (Integer) recyclerView.getTag();
horizontal_position = recyclerView.getChildAdapterPosition(recyclerView.getFocusedChild());
} else {
LinearLayout ll = (LinearLayout) view.findViewById(R.id.home_fragment_menu_container);
horizontal_position = ll.indexOfChild(ll.getFocusedChild());
}
}
}
}

Regarding (count down) timer for application in asp.net c#

Hi
I have created online quiz. I have added Count-down timer,label for question & radiobuttonlist for answers and next button for next question. I have code for timer but this timer gets start again when i click next button as i want count down timer for whole questions(Quiz).
Count down timer code(Javascript) is as follows:
var hour=0; //specify hours for counter
var min= '<%= Session["timer"] %>'; // specify minutes
var second = '<%= Session["second"] %>'; // specify the seconds
var lab = 'cd'; // id of the entry on the page where the counter(for question) is to be inserted & cd is span id in aspx page where i am displaying countdown timer
function start()
{
displayCountdown(setCountdown(hour,min,second),lab);
}
loaded(lab,start);
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f)
{
if (document.getElementById && document.getElementById(i) != null)
f();
else if (!pageLoaded)
setTimeout('loaded(\''+i+'\','+f+')',100);
}
function setCountdown(hour,min,second)
{
if(hour>0)
min=min*hour*60;
c = setC(min,second);
return c;
}
function setC(min,second)
{
if(min>0)
second=min*60*second;
return Math.floor(second);
}
function displayCountdown(countdn,cd)
{
if (countdn < 0)
{
document.getElementById(cd).innerHTML = "Sorry, you are too late.";
__doPostBack('__Page');
}
else
{
var secs = countdn % 60;
if (secs < 10)
secs = '0'+secs;
var countdn1 = (countdn - secs) / 60;
var mins = countdn1 % 60;
if (mins < 10)
mins = '0'+mins;
countdn1 = (countdn1 - mins) / 60;
var hours = countdn1 % 24;
document.getElementById(cd).innerHTML = hours+' : '+mins+' : '+secs;
setTimeout('displayCountdown('+(countdn-1)+',\''+cd+'\');',999);
}
}
You must keep a reference on "present" time relatively of the "start" time and the duration of the quiz. So, you would substract "present" time from start time.
protected int HoursDuration {
get {
if (Session["HoursDuration"] == null) { Session["HoursDuration"] = 0; }
return Convert.ToInt32(Session["HoursDuration"]);
}
set { Session["HoursDuration"] = value; }
}
protected int MinutesDuration {
get {
if (Session["MinutesDuration"] == null) { Session["MinutesDuration"] = 0; }
return Convert.ToInt32(Session["MinutesDuration"]);
}
set { Session["MinutesDuration"] = value; }
}
protected int SecondsDuration {
get {
if (Session["SecondsDuration"] == null) { Session["SecondsDuration"] = 0; }
return Convert.ToInt32(Session["SecondsDuration"]);
}
set { Session["SecondsDuration"] = value; }
}
protected int HoursLeft {
get {
return (this.EndTime - this.BeginTime).Hours;
}
}
protected int MinutesLeft {
get {
return (this.EndTime - this.BeginTime).Minutes;
}
}
protected int SecondsLeft {
get {
return (this.EndTime - this.BeginTime).Seconds;
}
}
protected DateTime EndTime {
get {
if (Session["EndTime"] == null) { Session["EndTime"] = DateTime.Now; }
return Convert.ToDateTime(Session["EndTime"]);
}
set { ViewState["EndTime"] = value; }
}
protected DateTime BeginTime {
get {
if (Session["BeginTime"] == null) { Session["BeginTime"] = DateTime.Now; }
return Convert.ToDateTime(Session["BeginTime"]);
}
set { ViewState["BeginTime"] = value; }
}
protected override void OnInit(EventArgs e) {
this.BeginTime = DateTime.Now; // Present time
if (!IsPostBack) {
// The countdown
this.HoursDuration = 0;
this.MinutesDuration = 10;
this.SecondsDuration = 0;
// Only on !postback, you set up when it ends
this.EndTime = this.BeginTime.AddHours(this.HoursDuration)
.AddMinutes(this.MinutesDuration)
.AddSeconds(this.SecondsDuration);
}
base.OnInit(e);
}
Then, in you javascript, call the HoursLeft, MinutesLeft and secondeLeft. I think this should work.

Resources