我正在使用Android Studio创建Android Launcher应用。
我尝试添加一项功能,允许用户选择已安装的小部件并将其放在我的启动器上。与游戏商店中的大多数发射器类似。
我的代码目前在cannot resolve symbol
和appWidgetHost
上发现了appWidgetManager
个错误。
我已经看过SO和Google如何实现这一点,但我仍然对如何使其工作以及如何纠正我的代码感到困惑。
这是我的代码:
package com.example.widgettest;
import android.app.Activity;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
Button widgetButton;
// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, 1);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();
// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addwidgetButtonListener();
}
public void createwidget(){
// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();
// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);
// Add it to your layout
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
rl.addView(hostView);
}
public void addwidgetButtonListener() {
widgetButton = (Button) findViewById(R.id.button);
widgetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
createwidget();
}
});
}
}
答案 0 :(得分:1)
Cannot resolve symbol
的一个原因是你没有声明一些变量。在这种情况下,您似乎忘记声明appWidgetManager和appWidgetHost。
您可以通过分别在AppWidgetManager
和AppWidgetHost
前加两行来修复此错误。像这样:
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
AppWidgetHost appWidgetHost = new AppWidgetHost(this, 1);
另一方面,我之前没有对Widget Manager或Widget Host做过任何工作,但一般来说,任何将Activity上下文作为参数的东西都应该在onCreate
函数中初始化。因此,如果您在调试应用程序时发现这些变量没有正确初始化,您可能希望这样做:
public class MainActivity extends Activity {
...
AppWidgetManager appWidgetManager;
AppWidgetHost appWidgetHost;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, 1);
...
}