从另一个类的 onCreate 中访问 ArrayAdapter
public class controller extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context currentContext = this;
final BlinkAPI blinkAPI = new BlinkAPI(currentContext);
lvRadio = (ListView)findViewById(R.id.ListViewRadio);
}
...
}
//***********************************
//Separate file
public class BlinkAPI {
private static Context mContext;
static ListView radioLV;
public BlinkAPI( Context ctx)
{
BlinkAPI.mContext = ctx;
radioLV = (ListView )((Activity) mContext).findViewById(R.id.ListViewRadio);
}
private static void updateRadioTitles( ) {
radioTitleAdapter = (ArrayAdapter<String>) radioLV.getAdapter();
...//Get titleStr etc
radioTitleAdapter.add(titleStr);
radioTitleAdapter.notifyDataSetChanged();
}
这段代码崩溃了
public class controller extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context currentContext = this;
final BlinkAPI blinkAPI = new BlinkAPI(currentContext);
lvRadio = (ListView)findViewById(R.id.ListViewRadio);
}
...
}
//***********************************
//Separate file
public class BlinkAPI {
private static Context mContext;
static ListView radioLV;
public BlinkAPI( Context ctx)
{
BlinkAPI.mContext = ctx;
radioLV = (ListView )((Activity) mContext).findViewById(R.id.ListViewRadio);
}
private static void updateRadioTitles( ) {
radioTitleAdapter = (ArrayAdapter<String>) radioLV.getAdapter();
...//Get titleStr etc
radioTitleAdapter.add(titleStr);
radioTitleAdapter.notifyDataSetChanged();
}
This code crashes out
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先:raukodraug 和 Flavio 是对的!您可以调用:
来获取ListView 的适配器。
不管你怎么说,你喜欢更新适配器。如果您想这样做,您的活动需要将该适配器作为变量保存,如下所示:
如果您现在想要更新适配器,您可以调用以下方法(确保您在 UI 线程上进行这些调用,否则列表视图不会更新):
First of all: raukodraug and Flavio are right! You cann call:
to get the adapter of the ListView.
However you said, that you like to update the Adapter. If you wanna do that, your activity needs to hold that adapter as a variable, like so:
If you now want to update the adapter you can call the following method (make sure that you make these calls on the UI-Thread, otherwise the listview wont be updated):
如果您有权访问
ListView
,则可以使用radioLV.getAdapter()
If you have access to the
ListView
you can useradioLV.getAdapter()
您可以通过调用 radioLV.getAdapter() 来获取适配器,
但您无法修改它(添加\删除项目)。要修改它 - 创建并设置新适配器,或者编写 ArrayAdapter 的扩展并向其添加 setObjects 方法。
You can obtain adapter by invoking radioLV.getAdapter()
But you cant modify it (add\remove items). To modify it - create and set new adapter, or write an extension of ArrayAdapter and add a method setObjects to it.