以编程方式将 TextView 添加到主屏幕小部件
我想以编程方式将文本视图控件添加到我的主屏幕小部件。在下面的示例中,我使用 TextView 填充 Linearlayout,但是这里应该如何使用 RemoteView?它只接受 xml 资源布局作为参数。
public class MyWidget extends AppWidgetProvider {
public void onUpdate(Context _context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
LinearLayout l = new LinearLayout(_context);
for (int i = 0; i < 10; i++) {
TextView t = new TextView(_context);
t.setText("Hello");
l.addView(t);
}
}
}
我看到的所有教程都显式地使用其预定义控件的值填充 RemoteViews 对象。我想以编程方式添加控件。
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.my_widget);
views.setTextViewText(R.id.widget_control1, value1);
views.setTextViewText(R.id.widget_control2, value2);
I want to programmatically add Text Views controls to my home screen widget. In the following example I populate Linearlayout with TextViews, but how should I use RemoteViews here? It only accepts xml resource layout as a parameter.
public class MyWidget extends AppWidgetProvider {
public void onUpdate(Context _context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
LinearLayout l = new LinearLayout(_context);
for (int i = 0; i < 10; i++) {
TextView t = new TextView(_context);
t.setText("Hello");
l.addView(t);
}
}
}
All tutorials I saw explicitly populate RemoteViews object with values for its predefined controls. And I want to add controls programmaticaly.
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.my_widget);
views.setTextViewText(R.id.widget_control1, value1);
views.setTextViewText(R.id.widget_control2, value2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在寻找我自己的答案时偶然发现了这个问题,虽然这不能回答我的问题,但我想我会回答这个问题。
假设您已经有一个小部件的布局文件
test.xml
。现在,创建一个新布局,例如保存到
text_view_layout.xml
。在该布局 xml 中,其内容如下:您现在刚刚创建了一个布局,其根视图是文本视图。
现在,在您的代码中,您可以向此文本视图添加文本,如下所示:
现在您刚刚创建了三个文本视图,所有文本均为“TextView number 0”等等...
我确信其他地方也有类似的答案,但是这是如何以编程方式将 textView 添加到 appWidget 中。
RemoteViews API
Stumbled upon this question in searching for my own answer, and while this doesn't answer my question i figured i would answer this question.
Assuming you already have a layout file for your widget,
test.xml
.Now, create a new layout, save e.g. to
text_view_layout.xml
. In that layout xml have this as its contents:You now just created a layout with its root view being a text view.
Now in your code you can add text to this text view like so:
Now you just created three textViews all with the text being "TextView number 0" and so on...
I'm sure there is a similar answer somewhere else, but this is how to programmatically add textViews to an appWidget.
RemoteViews API
好吧,对于appwidgets 来说这是不可能的。仅接受 xml 资源。
Ok, It is impossible for appwidgets. Only xml resources are accepted.
你可以试试这个
You could try this