[英]Hiding a MenuItem button and showing a ProgressBar in an ActionBar
我有一個包含片段的活動。 操作欄中有一個刷新按鈕,按下后,我想轉換為進度條以顯示活動。 雖然我收到以下錯誤:
無法啟動活動ComponentInfo {com.mycompany.myapp.Views.MasterDetails.MasterActivity}:java.lang.NullPointerException:嘗試調用接口方法'android.view.MenuItem android.view.MenuItem.setActionView(android.view.View) '在空對象引用上
在這一行: itemBtnRefresh.setActionView(abprogress);
一旦后台操作開始(“refreshData()”)
有關正確交換按鈕以獲取不確定進度條的任何幫助嗎?
public class MasterActivity extends AppCompatActivity {
private String TAG = getClass().getSimpleName();
private Toolbar mToolbar;
private ActionBar ab;
private MenuItem itemBtnRefresh;
private View abprogress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_master);
mToolbar = (Toolbar) findViewById(R.id.masterToolBar);
setSupportActionBar(mToolbar);
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
abprogress = inflater.inflate(R.layout.refresh_menuitem, null);
refreshData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
invalidateOptionsMenu();
getMenuInflater().inflate(R.menu.menu_master, menu);
itemBtnRefresh = menu.findItem(R.id.master_refresh_action);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.master_refresh_action:
refreshData();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void refreshData() {
//... do a background task
// show the progressbar and hide the refresh button
itemBtnRefresh.setActionView(abprogress);
//.. finish the background task
// hide progressbar and show button
itemBtnRefresh.setActionView(null);
}
}
menu_master.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/master_refresh_action"
android:icon="@drawable/ic_refresh"
android:title="Refresh"
app:showAsAction="ifRoom"/>
</menu>
refresh_menuitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:addStatesFromChildren="true"
android:focusable="true"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:gravity="center"
android:orientation="horizontal"
style="?attr/actionButtonStyle">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
style="@android:style/Widget.Holo.ProgressBar.Small"/>
</LinearLayout>
onCreateOptionsMenu
在onCreate
和你的第一個refreshData()
調用之后執行,所以'theitemBtnRefresh'仍為null。
在onCreateOptionsMenu
初始化itemBtnRefresh
后嘗試調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.