我想动态显示列表视图中的项目。在我的情况下,项目来自服务。服务广播该项目,活动接收它并填充数组中的项目,我用这个数组填充列表视图。
请你帮我知道我做错了什么?
这是我的代码:
public class MacaddressInfo extends AppCompatActivity {
ArrayList<String> listofMac=new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macaddress_info);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("intMAC"));
}
@Override
protected void onResume() {
super.onResume();
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleMessage(intent);
}
};
private void handleMessage(Intent msg){
if(msg != null) {
Bundle data = msg.getExtras();
String res = data.getString("result");
Log.d("macaddinfo", "macaddress info is: " + res);
listofMac.add(res);
lv = (ListView)findViewById(R.id.lstMac);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listofMac);
setListAdapter(adapter);
Log.i("handlemessage", "Array count is: " + listofMac.size() + " ListView count is: " + lv.getCount());
}
}
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(R.id.lstMac);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
}
在onhandlemessage()方法中,我正在填充数组并设置适配器,但我不确定为什么列表视图没有显示在屏幕上。即使我也得到了计数,&#34;我/ handlemessage:数组计数是:1 ListView计数是:1&#34;
以下是我的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="rockwell.bluetooth_pairing.MacaddressInfo"
tools:showIn="@layout/activity_macaddress_info">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="54dp" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/lstMac"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:choiceMode="singleChoice"/>
</RelativeLayout>
这是广播意图的服务代码,该意图将用作列表视图的值
public class APIService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
APIService getService() {
// Return this instance of LocalService so clients can call public methods
return APIService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void AddMacAddress(String str)
{
Log.d("APIService","message is: " + str);
Intent intent = new Intent("intMAC");
intent.putExtra("result",str);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Log.d("APIService", "intent broadcasted");
}
}
调用服务的代码
public class MainActivity extends AppCompatActivity {
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
int clickCounter=0;
ListView lv;
EditText txtIP;
Button btnAdd,btnUpdate,btnDel;
int itemPos;
APIService mservice;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txtIP = (EditText)findViewById(R.id.txtIP);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
lv = (ListView)findViewById(R.id.lstItems);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listItems);
setListAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
txtIP.setText(listItems.get(position));
itemPos = position;
Log.d("onlongclickpos", "long click pos is: " + position);
return true;
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,MacaddressInfo.class);
startActivity(intent);
mservice.AddMacAddress("TestMAC");
}
});
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, APIService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
APIService.LocalBinder binder = (APIService.LocalBinder) service;
mservice = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public void addItems(View v) {
txtIP = (EditText)findViewById(R.id.txtIP);
String strItem = txtIP.getText().toString();
listItems.add(strItem);
adapter.notifyDataSetChanged();
}
public void updateItem(View v) {
//txtIP = (EditText)findViewById(R.id.txtIP);
String strItem = txtIP.getText().toString();
//Toast.makeText(this,"pos is " + lv.getCheckedItemPosition(),Toast.LENGTH_LONG).show();
int pos = itemPos;
if(pos > -1) {
adapter.remove(listItems.get(pos));
adapter.insert(strItem, pos);
}
adapter.notifyDataSetChanged();
}
public void delItem(View v) {
//int pos = lv.getCheckedItemPosition();
int pos = itemPos;
if(pos>-1)
{
adapter.remove(listItems.get(pos));
}
adapter.notifyDataSetChanged();
}
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(R.id.lstItems);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
首先尝试在onCreate
中分配和初始化视图和适配器,然后在handleMessage
中,您可以添加到列表并调用adapter.notifyDataSetChanged()
告诉适配器更新ListView。
此外,经过一些工作,使listOfMac
静态最终解决问题。我认为之前在日志中发生的事情是你抓住了MacAddressInfo
类的旧实例,所以那些ListView
计数正在递增,而不是当前显示的计数。
代码看起来像这样
public class MacAddressActivity extends AppCompatActivity {
// Static variables shared at class-level
private static final ArrayList<String> listofMac = new ArrayList<String>();
private static boolean mRegistered;
private ArrayAdapter<String> adapter;
private ListView lv;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
handleMessage(intent);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macaddress_info);
lv = (ListView) findViewById(R.id.lstMac);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listofMac);
lv.setAdapter(adapter);
// fab code
}
@Override
protected void onStart() {
super.onStart();
// prevent from registering again
if (!mRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("intMAC"));
mRegistered = true;
}
}
@Override
protected void onPause() {
super.onPause();
// Should be unregistered, but uncommenting this makes it stop working
/*
if (mRegistered) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
mRegistered = false;
}
*/
}
private void handleMessage(Intent msg) {
if (msg != null) {
Bundle data = msg.getExtras();
String res = data.getString("result");
Log.d("macaddinfo", "macaddress info is: " + res);
listofMac.add(res);
adapter.notifyDataSetChanged();
Log.i("handlemessage", "Array count is: " + listofMac.size() + " ListView count is: " + lv.getCount());
}
}
}