大家好,我希望你能提供帮助。
我已经构建了一个填充ListView的RSS阅读器。我想检查用户是否有应用程序启动时的网络访问权限,如果没有网络,则用户应该看到setEmptyView View和Toast。
在onCreate中我已经为列表适配器设置了一个空列表,所以我希望看到空视图。然后我查询网络状态,如果没有网络,我创建一个祝酒词。但我从来没有看到启动时的空视图,当我没有网络时,我从未看到吐司。怎么回事?
public class XMLActivity extends ListActivity {
private List<JSONObject> jobs = new ArrayList<JSONObject>();
private RssListAdapter adapter;
private ListView lv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//SET LAYOUT WITH EMPTY LIST VIEW
setContentView(R.layout.main);
View empty = findViewById(R.id.empty);
lv = getListView(); //get view layout
lv.setEmptyView(empty); //set empty view
adapter = new RssListAdapter(this,jobs); //jobs is empty array list
setListAdapter(adapter);
//CHECK FOR NETWORK AND DISPLAY TOAST
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
// START RSS READER HANDLER
try {
jobs = RssReader.getLatestRssFeed();
} catch (Exception e) {
}
//REFRESH ADAPTER FOR LISTVIEW
adapter.clear();
for(JSONObject job :jobs){
adapter.add(job);
}
adapter.notifyDataSetChanged();
lv.setClickable(true);
为什么我看不到空视图或吐司,这个问题只发生在onCreate例程中。稍后的toast和空视图在菜单项选择上显示正常,因此它似乎是onCreate序列特有的问题。
答案 0 :(得分:0)
尝试Toast.makeToast(this, "msg to user", Toast.TOAST_MSG_SHORT).show();
我确定我在那里有一个拼写错误,因为我还没有启动和运行(还)。
答案 1 :(得分:0)
使用:
Toast.makeText(XMLActivity.this , "No Network", Toast.LENGTH_LONG).show();
答案 2 :(得分:0)
if (!network){
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
TextView txt1 = new TextView(this);
txt1.setText("No Network");
toast.setView(txt1);
toast.show();
}
else ...
试试这个.. ,,。
答案 3 :(得分:0)
您有一个未涵盖的情况 - 如果network
== true
会怎样?
try{
boolean network = RssReader.isOnline(this); //check network state
if (!network){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(XMLActivity.this, "Network Access!", Toast.LENGTH_LONG);
toast.show();
}
}catch (Exception e){
Toast toast = Toast.makeText(XMLActivity.this, "No Network Access", Toast.LENGTH_LONG);
toast.show();
}