我试图从Fragment中获取动态添加到Activity的视图。
MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
myDrawerList.setOnItemClickListener(new DrawerItemClickListener());
handleIntent(getIntent());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(
AdapterView<?> parent, View view, int position, long id
) {
// display view for selected nav drawer item
displayView(position);
}
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String userToken = UserTokenStorageFactory.instance().getStorage().get();
switch (position) {
case 0:
fragment = new AllCategories();
break;
case 1:
fragment = new Subscription();
break;
case 2:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, PrivateOffice.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 3:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, Create_action.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 4:
AlertDialog dialog = onCreateDialog(DIALOG_CHOOSE_CATEGORY);
dialog.show();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fTrans = fragmentManager.beginTransaction();
fTrans.replace(R.id.content_frame, fragment);
fTrans.commit();
// update selected item and title, then close the drawer
myDrawerList.setItemChecked(position, true);
myDrawerList.setSelection(position);
setTitle(viewsNames[position]);
myDrawerLayout.closeDrawer(mDrawer);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
我需要从AllCategories.java的布局中获取视图(LinearLayout listv)。我尝试将findView()与findViewById一起使用,但它返回NullPointerException。我该怎么办?