I have a kv segment that is within my python code.
What I want to do is select this button and animate it. The animation itself is triggered by pressing NoButton. NoButton has a class of itself that is child to the root widget class. Unfortunately despite having been able to successfully reference id out of the kv code, i can't seem actually make use of it.
Pressing NoButton results in absolutely nothing. No errors, nothing. If I try to print the id what i get is the location of the button it references:
<__main__.MainButton object at 0x7fd5db0d5590>
Here is a snippet of the kv code:
<MainClass>:
<MainScreen>:
id: main
AnchorLayout:
size: root.size
anchor_x: 'center'
anchor_y: 'center'
padding: 0, 0, 0, 50
MainButton:
id: pics
rgba: 1,5,1,1
size_hint_x: None
size_hint_y: None
height: main.height / 1.5
width: main.width / 1.5
and the python:
class MainScreen(Screen):
pass
class MainButton(Button):
pass
class NoButton(ButtonBehavior, Image, MainClass):
def on_press(self):
anim = Animation(x=300, y=300)
anim.start(MainButton())
print(MainScreen().ids.pics)
You'll notice anim.start references the class rather than the id here. Unfortunately it produces the same result; nothing at all.
Creating pics as an object property and declaring that in kv fails to work too.
I really am completely clueless here. I've looked through the few questions that are slightly similar but there really isn't much when it comes to help/guides for in depth kivy development.
I'm using Python 3.5.3 and Kivy 1.9.2-dev0
Would appreciate any help/advice or pointers in the right direction :)
You are creating new objects instead of referencing the exiting ones
anim.start(MainButton()) #new MainButton Object :(
print(MainScreen().ids.pics) #also a new MainScreen object
I don't see in your code where is NoButton, but should get a hold on the MainScreen instance and from it extract the MainButton instance
main_button = main_screen.ids.pics
ani.start(main_button)
If you'll post a runable example I'll might be able to help you more, I guess...
Related
I'need to show user feed with items where every item contain a chart.
Now I use react-native-svg-charts:
<LineChart
style={{ height: 150, position: 'relative', left: -20 }}
data={data}
curve={shape.curveNatural}
svg={{ stroke: chartColor1, strokeWidth: 5 }}
contentInset={{ top: 20, bottom: 20 }}
showGrid={false}
numberOfTicks={0}
key={props.id}
>
But when I load more then 50 items performance of the app fall down to 10-15 fps.
I think it because of many SVG's on page. Which solution do you think should I use to avoid this?
I answered a similar question recently here: Real-time data update chart in React Native and will suggest the same here.
I've struggled with performance when plotting in React Native with all of the SVG-based libraries I've tried. I recently decided to try using a couple canvas-based plotting libraries within a WebView and had very good results. I ended up making a simple package: https://www.npmjs.com/package/#dpwiese/react-native-canvas-charts.
Should you not want to use this package and instead do it yourself, it's quite straightforward. While the package source code is probably the best resource I'll summarize the steps below:
Create an HTML file and import it into your component:
const htmlTemplate = require("./index.html");
where the HTML contains the JavaScript for the charting library of choice. The linked package above currently supports Chart.js v3 and uPlot. In the steps below I'll show a Chart.js configuration.
Create a ref, for example let webref.
Create a WebView and onLoadEnd you can inject some JavaScript into the WebView that will configure and create your chart
<WebView
originWhitelist={["*"]}
ref={r => (webref = r)}
source={htmlTemplate}
onLoadEnd={() => { addChart(config) }}
/>
where addChart looks something like:
const addChart = config => {
webref.injectJavaScript(`const el = document.createElement("canvas");
document.body.appendChild(el);
window.canvasLine = new Chart(el.getContext('2d'), ${JSON.stringify(config)});`);
};
and config is a valid Chart.js configuration.
To update the chart data simply inject some JavaScript to update the data. In the case of Chart.js here, that'd look like:
const setData = dataSets => {
if (dataSets) {
dataSets.forEach((_, i) => {
webref.injectJavaScript(`window.canvasLine.config.data.datasets[${i}].data = ${JSON.stringify(dataSets[i])};
window.canvasLine.update();`);
});
}
};
where dataSets are valid Chart.js data sets.
That's it! I've only played around with these two plotting libraries via the https://www.npmjs.com/package/#dpwiese/react-native-canvas-charts package, but so far performance has been really good, even with the JSON stringification of all the passed chart data. I haven't quantified it thoroughly, but both libraries are orders of magnitude more performant than any of the SVG-based ones I've tried.
thank you for your time.
I have an APP I'm working on. I'm trying to automate something where every word I write in the MDTextField id: sent is turned into it's own MDChip id: chip to be selected later on by the user.
The closest I've gotten is using this:
class Main(Screen):
"""main application goes here"""
def my_callback(dt):
def __init__(self):
sent = self.ids.sentence.text.lower()
print(sent)
for word in sent.split():
c = MDChip(label=word, icon='check')
self.ids.chip.add_widget(c)
Clock.schedule_interval(my_callback, 0.5)
But it doesn't work. def init(self) never actually runs it seems... idk... I have verified that the my_callback function is getting called properly by the Clock but that's as far as it goes.
Any thoughts anyone..?
Maybe there is a better function inside Kivy that is called anytime something is typed in a textfield?? That would be perfect I think...
Ultimately I want to use one of the MDChip selected by the user and replace their sentence with a new word. I truly appreciate any help.
Your my_callback() method is just defining another method named __init__(), without actually calling that new method. That is an inner function and is not visible outside of my_callback().
Try changing my_callback() to:
def my_callback(self, dt):
sent = self.ids.sentence.text.lower()
print(sent)
for word in sent.split():
c = MDChip(label=word, icon='check')
self.ids.chip.add_widget(c)
Also, an __init__() method is the method used to initialize a Widget, and it's not good programming practice to use that method name for other purposes.
Here what I finally found with some help. Thanks all.
class Main(Screen):
def on_pre_enter(self):
Window.bind(on_key_down=self.call)
def call(self, *args):
self.ids.stack.clear_widgets()
sent = self.ids.sentence.text.lower()
for word in sent.split():
c = MDChip(label=word,
callback=self.do_something,
icon='checkbox-blank-outline',
color=[.1, .1, .1, .5],)
self.ids.stack.add_widget(c)
def do_something(self, inst, word, *args):
inst.icon = 'checkbox-marked-outline'
WORD = word
print(WORD)
return WORD
Using the Window.bind inside the on_pre_enter was the most important thing. Then it all worked. Here is my KV code:
MDStackLayout:
id: stack
orientation: 'lr-tb'
pos_hint: {'center_x': 0.5, 'center_y': 0.6}
padding: dp(8)
spacing: dp(8)
I have a quite typical problem of laggy animations during component rendering. However, as far as I understand, the common solutions I found in the documentation of react-native cannot be applied to my use case.
Let me explain: I have a tab pager implemented with (i) a ViewPagerAndroid containing a set of pages and (ii) a tab bar composed of a set of touchables and a line (Animated.View) that moves (translateX transform) when the pager X-scroll value changes.
Each page component follows the same logic:
when componentDidMount is called, it triggers a network call for loading data
once the data are loaded, the state is updated with the new data and the component is rerendered
the render method simply returns a FlatList that displays the loaded data (20 items only)
My problem is: if the user clicks on a tab while the pages are rendered, the animations are horribly laggy. Given that the animation and the rerendering are performed on the UI thread, I'm guessing that they are competing in some way.
I eliminated various causes, but wasn't able to find a proper solution to keep the animation fluid:
I replaced the network call with hardcoded data and a simple timeout; the UI is still laggy when the pages are rerendered
I tried to improve the rerendering time, but the FlatList is quite slow even using pure components.
I tried in release mode and there is no differences
The problem occurs also on a physical device (Nexus 5X, which is quite powerful)
It's not specific to my implementation, I tried github.com/skv-headless/react-native-scrollable-tab-view and github.com/zbtang/React-Native-ViewPager
I know about InteractionManager and TimerMixin.requestAnimationFrame, but it's useless in my case: when the rendering is started, the user can still click on the tab bar buttons and it's not an option to wait the end of the render (laggy).
I uploaded my code in a github repository (https://github.com/benjaminbillet/tabbartest), in case you want to have more details. It's quite straightforward, but don't hesitate to ask me more details.
Some additional information:
react-native 0.46.4
node 8.2.0
npm 5.3.0
tried only on Android.
Do you think I should fill a bug report?
Thanks a lot.
EDIT-1 Here is a simplified version of the animation code:
render() {
const underlineStyle = {
position: 'absolute',
left: 0,
bottom: 0,
width: this.tabWidth,
height: underlineHeight,
backgroundColor: underlineColor,
transform: [{
translateX: this.pagerScrollX.interpolate({
inputRange: [0, 1],
outputRange: [0, this.tabWidth],
}),
}],
};
return (
<View style={[styles.tabs, style]}>
...
<Animated.View style={underlineStyle} />
</View>
);
}
onPageScroll(offset) {
const { offset, position } = e.nativeEvent;
this.pagerScrollX.setValue(position + offset);
}
I'm new to Xamarin and I'm trying to use the Iconize NuGet package for Xamarin, but I'm not having much luck. At the moment I'm working with a simple Android app. I've installed Iconize per the instructions and, save for an error on the line:
FormsPlugin.Iconize.Droid.IconControls.Init(Resource.Id.toolbar, Resource.Id.tabs);
(the compiler didn't like the Resource.Id.toolbar or Resource.Id.tabs so I removed it) everything compiles and runs. However, when I try to add an IconButton with a Fontawesome image, I get "System.NullReferenceException: Object reference not set to an instance of an object." error that points back to
the line LoadApplication( new App() ); in the MainActivity.cs.
I'm trying to add the IconButton to a grid in code (not XAML) using
grid.Children.Add( new IconButton
{
Image = "fa-info-circle"
}, 3, 2 );
Any ideas on how to make this work? The examples on the Iconize page haven't been very useful and I haven't found any examples on Google.
Okay I finally found something that was useful. I found a clue on this page and some other information on the project issues page on Github.
Ultimately, to get the icon to display I used
grid.Children.Add( new IconButton
{
Text = "fa-info-circle",
}, 3, 2 );
It was the Text property and not the Image property that I should have used.
Hope this helpful to someone else.
im developing an APP in corona SDK, it's a serie of tests, so i made every test separately and then i created a main Scene that contains this tests. To handle any click error or misunderstanding i created a "back to intro" button, the problem is, when i start a test (for example test2) i'm in the middle of the test and i use the back to intro button (that takes me to intro, there's no prob with that) the Test2 keeps going and when i try to re-take the test shows an error related to this. I've trying different ways but i can't make it work, here is the code of the button:
local function handleButtonEvent( event )
if ( "ended" == event.phase ) then
storyboard.showOverlay( "cerrar sesion", options )
end
end
local button1 = widget.newButton
{
width = 60,
height = 60,
defaultFile = "images/boton_config.png",
overFile = "images/boton_config.png",
label = "",
onEvent = handleButtonEvent
}
-- Center the button
button1.x = display.contentCenterX+550
button1.y = 35
button1.isVisible=true;
storyboard.gotoScene("test0intro")
Plz help :<
I think I may have had this problem. I would advise switching to composer rather than storyboard a lot of these issues are easier to find. I am unsure about storyboard but for composer I know that I had to remove all event listeners, remove the sceneGroup, stop the physics and then remove the scene in the scene:hide method. I'm unsure of what the equivalent of this is in storyboard. Otherwise when I went to restart to the game (as you seem to be doing), the game would crash. Hope that helps!