我有一個包含片段的活動。在操作欄中有一個刷新按鈕,當按下時,我想要轉換爲進度條來顯示活動。雖然我收到以下錯誤:隱藏MenuItem按鈕並在ActionBar中顯示ProgressBar
Unable to start activity ComponentInfo{com.mycompany.myapp.Views.MasterDetails.MasterActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setActionView(android.view.View)' on a null object reference
在此行中:儘快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>