我正在用Java开发android应用程序,我必须在小部件中创建一些按钮,这些按钮是动态添加的。我尝试了很多解决方案,但是它们无法正常工作,因此请不要将此问题标记为重复。这是我的Widget.java:
package com.fxteam.malcome;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Button;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.util.Log;
public class Widget extends AppWidgetProvider {
private static final String SYNC_CLICKED = "malcome_widget_button";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Intent intent2 = new Intent(context, MainActivity.class);
intent2.putExtra("accountID", "0");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.simple_app_widget);
views.setOnClickPendingIntent(R.id.malcome_widget_button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
/*Button myButton = new Button(context);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout) findViewById(R.id.widget_layout); //<- this give me error "cannot find symbol method findViewById(int)"
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);*/
}
}
您可以使用:
private Button button;
private LinearLayout linearLayout;
private final int USERID = 6000;
private int countID;
button = (Button) findViewById(R.id.button);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = new Button(getApplicationContext());
b.setText("text on btn " + Integer.toString(countID + 1));
b.setLayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT)
);
b.setId(USERID + countID);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// to do
}
});
linearLayout.addView(b);
countID++;
}
});
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。