I made a drawer navigation based on a tutorial on the internet and I followed everything but when I open my app everything is working correctly except my onclick event. I'm pretty new to android (2 weeks) and tried to figure it out by myself but it didn't work out. I tries onclicklistener but that one didn't give any possitive feedback for me.
How do I make a click event that will take me to another activity?
my code:
public class LayoutOneActivity extends ActionBarActivity {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_one);
Resources res = getResources();
String [] menu_items = res.getStringArray(R.array.menu_items); // String array where the menu items will be stored
menu = menu_items; // Variable for the menu items
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Looking for the id "drawer_layout" and apply as layout
dList = (ListView) findViewById(R.id.left_drawer); // Looking for the listview where the items will be stored
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);// Making a new adapter
dList.setAdapter(adapter);// Give the list-layout the variable "adapter" which is an adapter (obviously)
dList.setSelector(R.drawable.back);// Sets the colour of the list-layout
dList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
{
dLayout.closeDrawers();// The layout will be clossed when clicked outside the layout
Bundle args = new Bundle();// New bundle which will parse the data between various activities
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
});
}
layout_one
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal">
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity1"
android:text="#string/clickActivity1" />
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity2"
android:text="#string/clickActivity2" />
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity3"
android:text="#string/clickActivity3" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal">
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity4"
android:text="#string/clickActivity4"/>
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity5"
android:text="#string/clickActivity5"/>
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity6"
android:text="#string/clickActivity6"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff"/> </android.support.v4.widget.DrawerLayout>
menu_detail_fragment
<?xml version="1.0" encoding="utf-8"?> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:gravity="center"
android:background="#5ba4e5"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="#ffffff"
android:layout_gravity="center"
android:id="#+id/detail"/> </LinearLayout>
To set a navigation menu onClickListener you have to implement the NavigationView.OnNavigationItemSelectedListener interface on the Activity.
On the onCreate method you have to define the navigation onClickListener to the context Activity like this:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Then you have to Override the method
#Override
public boolean onNavigationItemSelected(MenuItem item)
I write an example of how to implement the method below:
#Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Urban");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_gallery) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Cosmos");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_slideshow) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Sink");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_share) {
ShopListFragment intent = new ShopListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, intent).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(START);
return true;
}
Related
I know this issue has been put out there 100 times, but nothing I've seen solves this. I have a button in a layout called fragment_main which is shown to another layout: activity_main. That button opens a fragment called AddEditFragment, which allows users to add info to a form that then spits it into a recyclerview(fragment_main) that is shown in MainActivity.
I have both layouts due to having a navigation drawer in a linearlayout in activity_main and the recyclerview and button in fragment_main constraintlayout. However I have onDelete/Edit/Save methods already up and going in MainActivity, so it only makes sense to me to put the button onClickListener there as well. Except since the button isn't in the main layout, activity_main, I get a fatal null object exception.
Even though fragment_main is shown in activity_main is there a way around this so the OnClick method can be put into MainActivity for a button in a linked layout?
MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnVehicleClickListener,
FragmentAddEdit.OnSaveClicked,
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// Launcher view
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
navigationView.setCheckedItem(R.id.nav_garage);
}
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_garage:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
break;
case R.id.nav_history:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentHistory()).commit();
break;
case R.id.nav_upcoming:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentUpcoming()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentAbout()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveClicked() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (AddEditFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(AddEditFragment)
.commit();
}
}
public void onEditClick(#NonNull Vehicle vehicle) {
AddEditRequest(vehicle);
}
#Override
public void onDeleteClick(#NonNull Vehicle vehicle) {
}
private void AddEditRequest(Vehicle vehicle) {
Intent detailIntent = new Intent(this, FragmentAddEdit.class);
if (vehicle != null) {
detailIntent.putExtra(Vehicle.class.getSimpleName(), vehicle);
startActivity(detailIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".com.carupkeep.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".com.carupkeep.FragmentMainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/no_vehicles"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/no_vehicle_message"
android:textSize="22sp"
android:textStyle="normal|bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"/>
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
<android.support.v7.widget.RecyclerView
android:id="#+id/vehicle_list"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/no_vehicles"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
UPDATE
I got close but still feel so far. I've given up on trying to keep it in MainActivity and put it in FragmentMainAcitivity as suggested. Except now I have 2 can't resolve errors. The first being on view in view.findViewById button initialization AND on fragment_container in the callback method. Any thoughts on how to resolve this?
public class FragmentMainActivity extends Fragment {
Button button_add = view.findViewById(R.id.button_add);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction().replace(fragment_container, AddEditFragment).commit();
}
});
}
}
easier way to do it is to put
onClick="AddEditRequestView"
in your fragment_main.xml
so it will be
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
android:onClick="AddEditRequestView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
and in your MainActivity.java
add this method
public void AddEditRequestView(View viewc){
AddEditRequest(null);
}
and delete these code from your activity
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
I'm developing an application (as my first one) and In this app I've declared my navigationView like this:
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_drawer"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_menu"
app:headerLayout="#layout/drawer_header">
In my mainactivity.java I have:
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
...
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d("Navigation","Item selected : "+ item.getItemId());
int id = item.getItemId();
switch (id){
case R.id.about:
Toast.makeText(getApplicationContext(),"About Us
elected",Toast.LENGTH_SHORT).show();
break;
case R.id.help:
Toast.makeText(getApplicationContext(),
"Help",Toast.LENGTH_SHORT).show();
break;
case R.id.setting:
Toast.makeText(getApplicationContext(),
"Settings",Toast.LENGTH_SHORT).show();
break;
case R.id.EditProfile:{
Intent intent= new Intent(this , EditProfile.class);
startActivity(intent);
}
default:
break;
}
DrawerLayout drawerLayout= (DrawerLayout)
findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return false;
}
And according to this I've extended ActionBarDrawerToggle and in it's onDrawerOpened function I've don
drawerView.bringToFront();
drawerView.getParent().requestLayout();
But still when I click on navigation view Items onNavigationItemSelected function doesn't fire.
Is it because of header view I have added??
This method worked before I add header view to navigationView( I didn't test it just before adding header to navigationView.
And also I think it's useful to note that I have some buttons and TextViews in navigationView header.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:id="#+id/drawer_header"
android:background="#drawable/drawer_bg"
android:layout_width="match_parent"
android:padding="4dp"
android:layout_height="200dp">
<RelativeLayout
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/avatar"
android:id="#+id/AvatarImageView"
android:layout_centerHorizontal="true" />
<Button
android:text="Signup"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentRight="true"
android:id="#+id/header_signup"
android:textSize="12sp"
android:background="#drawable/signup_button"
android:textStyle="normal|bold" />
</RelativeLayout>
<TextView
android:textColor="#color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:id="#+id/header_username"
android:textAlignment="center" />
<TextView
android:text="Logout"
android:textColor="#color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:layout_height="wrap_content"
android:id="#+id/header_logout"
/>
</LinearLayout>
You should add following line of code in onCreate for click listener for menu item,
NavigationView navigationView = (NavigationView) findViewById(R.id. navigation_drawer);
navigationView.setNavigationItemSelectedListener(this);
You can set click listener to the header of the NavigationView like this:
View headerLayout = navigationView.getHeaderView(0);
headerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(this , EditProfile.class);
startActivity(intent);
});
and for the elements inside the header
CircleImageView userPicture = (CircleImageView) headerLayout.findViewById(R.id.AvatarImageView);
Edit
navigationView.setNavigationItemSelectedListener(this);
This is the solution:
path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/WhatsApp/Media/.Statuses/";
File f= new File(path);
I am trying to add a fragment from an activity using the add(R.id.containerId, fragment);. However the log gives the java.lang.IllegalArgumentException: No view found for id error.
The fragment layout contains an id in the root element. I know that placing the container id in a child element is supposed to fix things, but this has made no difference for me.
Here is the root element in the fragment layout xml file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical"
tools:context=".view.fragment.Fragment">
Here is the onCreate() method in my activity:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragment);
currentFragment = R.id.fragment_container;
transaction.commit();
Here is the onCreateView() method in the fragment:
return inflater.inflate(R.layout.fragment, container, false);
Here is the entire activity code (the naming and ids are different because I changed them in the snippets above, imports statements are also missing for brevity):
public class MainActivity extends AppCompatActivity {
private int currentFragmentId;
private FeedFragment feedFragment = new FeedFragment();
private EventsFragment eventsFragment = new EventsFragment();
private SearchFragment searchFragment = new SearchFragment();
private MoreFragment moreFragment = new MoreFragment();
// Add other fragments
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_feed_container, feedFragment);
currentFragmentId = R.id.fragment_feed_container;
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_feed:
// Add the feed fragment
replaceFragment(feedFragment, currentFragmentId);
currentFragmentId = R.id.fragment_feed_container;
return true;
case R.id.action_events:
// Add the events fragment
replaceFragment(eventsFragment, currentFragmentId);
currentFragmentId = R.id.fragment_events_container;
return true;
case R.id.action_search:
// Add the search fragment
replaceFragment(searchFragment, currentFragmentId);
currentFragmentId = R.id.fragment_search_container;
return true;
case R.id.action_more:
// Add the more fragment
replaceFragment(moreFragment, currentFragmentId);
currentFragmentId = R.id.fragment_more_container;
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
/**
* Replaces the current fragment with a new fragment
*
* #param newFragment
* #param currentFragmentId
*/
private void replaceFragment(Fragment newFragment, int currentFragmentId) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(currentFragmentId, newFragment);
transaction.commit();
}
}
Here is the full fragment class (the naming and ids are different because I changed them in the snippets above, imports statements are also missing for brevity):
public class FeedFragment extends Fragment {
public View mView;
public FeedFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_feed, container, false);
return mView;
}
}
Here is the code for the full fragment_feed.xml file (the naming and ids are different because I changed them in the snippets above, imports statements are also missing for brevity):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_feed_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical"
tools:context=".view.fragment.FeedFragment">
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
card_view:cardBackgroundColor="#fff"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/top_card_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="6dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/card_profile_image_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start" />
<TextView
android:id="#+id/card_info_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="6"
android:gravity="start"
tools:text="Julien Durrand invited you" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
tools:text="3 months" />
</LinearLayout>
<ImageView
android:id="#+id/card_main_image_view"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/top_card_linear_layout"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="12dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/card_main_image_view"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="6dp"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="start"
tools:text="30K" />
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center" />
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center" />
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:gravity="center" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Here is the main parts of the logcat stacktrace (the naming and ids are different because I changed them in the snippets above, imports statements are also missing for brevity):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomfinet.magpie/com.tomfinet.magpie.view.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0c0076 (com.tomfinet.magpie:id/fragment_feed_container) for fragment FeedFragment{c9899d7 #0 id=0x7f0c0076}
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0076 (com.tomfinet.magpie:id/fragment_feed_container) for fragment FeedFragment{c9899d7 #0 id=0x7f0c0076}
Stuff that I have checked:
Fragment layout is correct in the onCreateView() method in the fragment.
Fragment layout container id in child of the fragment xml file.
How do I fix this error?
Thank you.
When I change the layout of a fragment within an activity, the menu options in the action bar seem to stop working. The buttons (Search icon and NavDrawer icon) become unresponsive.
This is the layout file of the fragment with the working menu options:
activity_login.xml (working)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Login."
android:id="#+id/login_title_text"
android:layout_alignParentTop="true"
android:textSize="40sp"
android:layout_marginTop="100dp"
android:fontFamily="sans-serif-light"
android:textColor="#color/colorAlt"
android:layout_centerHorizontal="true" />
<!-- E-mail section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="E-mail address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:ems="10"
android:id="#+id/login_emailField"
android:layout_above="#+id/login_passwordField" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_email_icon"
android:layout_alignBottom="#id/login_emailField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<!-- Password section -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_password_icon"
android:layout_alignBottom="#id/login_passwordField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:hint="Password"
android:id="#+id/login_passwordField"
android:layout_centerVertical="true"
android:layout_marginLeft="50dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="25dp" />
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_login_button"
android:layout_gravity="center_vertical"
android:layout_below="#+id/login_passwordField"
android:layout_marginBottom="29dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
card_view:cardBackgroundColor="#E91E63"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="6dp">
<TextView
android:id="#+id/material_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="13dp"
android:paddingBottom="13dp"
android:layout_gravity="center_horizontal"
android:textColor="#FFF"
android:textSize="19sp"
android:fontFamily="sans-serif-medium"
android:text="Login" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Forgotten your username or password?"
android:layout_below="#id/login_login_button"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/login_footer_text"
android:layout_marginTop="40dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tap here"
android:textColor="#000000"
android:layout_below="#id/login_footer_text"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/loginForgottenTapText"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</LinearLayout>
This is the layout file that seems to break the buttons:
activity_login.xml (non-working)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Login."
android:id="#+id/login_title_text"
android:layout_alignParentTop="true"
android:textSize="40sp"
android:layout_marginTop="100dp"
android:fontFamily="sans-serif-light"
android:textColor="#color/colorAlt"
android:layout_centerHorizontal="true" />
<!-- E-mail section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="E-mail address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:ems="10"
android:id="#+id/login_emailField"
android:layout_below="#+id/login_title_text" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_email_icon"
android:layout_alignBottom="#id/login_emailField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<!-- Password section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:hint="Password"
android:layout_below="#id/login_emailField"
android:id="#+id/login_passwordField"
android:layout_marginLeft="50dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="25dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_password_icon"
android:layout_alignBottom="#id/login_passwordField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_login_button"
android:layout_gravity="center_vertical"
android:layout_below="#+id/login_passwordField"
android:layout_marginBottom="29dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
card_view:cardBackgroundColor="#E91E63"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="6dp">
<TextView
android:id="#+id/material_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="13dp"
android:paddingBottom="13dp"
android:layout_gravity="center_horizontal"
android:textColor="#FFF"
android:textSize="19sp"
android:fontFamily="sans-serif-medium"
android:text="Login" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Forgotten your username or password?"
android:layout_below="#id/login_login_button"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/login_footer_text"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tap here"
android:textColor="#000000"
android:layout_below="#id/login_footer_text"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/loginForgottenTapText"
android:layout_marginTop="10dp"/>
</RelativeLayout>
</ScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, LoginFragment.OnLoginCallback {
MenuItem register;
MenuItem login;
MenuItem logout;
MenuItem completeListing;
MenuItem expiredListing;
MenuItem activeListing;
NavigationView navigationView;
UserCredentialHandler userStatus;
protected static final String KEY_USER_STATUS = "USER_STATUS";
protected static final String USER_PREFS = "userNamePrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userStatus = new UserCredentialHandler();
final HomeFragment homeFragment = new HomeFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), CreateListingActivity.class);
startActivity(i);
}
});
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getMenuItems(navigationView);
if(userStatus.checkIfUserIsLoggedIn(getApplicationContext())){
userStatus.setNavHeaderOnLogin(getApplicationContext(), navigationView);
updateNavDrawer("login", register, login, logout, expiredListing, completeListing, activeListing);
} else {
userStatus.setNavHeaderOnLogout(navigationView);
updateNavDrawer("logout", register, login, logout, expiredListing, completeListing, activeListing);
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_container,homeFragment);
fragmentTransaction.commit();
}
#Override
public void onLoginSuccess() {
HomeFragment homeFragment = new HomeFragment();
userStatus.setNavHeaderOnLogin(getApplicationContext(), navigationView);
updateNavDrawer("login",register,login,logout, expiredListing, completeListing, activeListing);
register.setVisible(false);
login.setVisible(false);
logout.setVisible(true);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_container,homeFragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_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;
} else if (id == R.id.search_mag_icon){
SearchFragment searchFragment = new SearchFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, searchFragment)
.addToBackStack(null)
.commit();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_register) {
final RegisterFragment registerFragment = new RegisterFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, registerFragment)
.addToBackStack(null)
.commit();
} else if (id == R.id.nav_login) {
final LoginFragment loginFragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, loginFragment)
.addToBackStack(null)
.commit();
} else if(id == R.id.nav_logout) {
userStatus.logoutUser(getApplicationContext());
userStatus.setNavHeaderOnLogout(navigationView);
updateNavDrawer("logout",register,login,logout, expiredListing, completeListing, activeListing);
} else if (id == R.id.nav_my_listings) {
// navigate to my listings
} else if (id == R.id.nav_how) {
// navigate to how it works page
} else if (id == R.id.nav_help) {
// navigate to help page
} else if (id == R.id.nav_contact_us) {
// navigate to contact page,
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void updateNavDrawer(String action, MenuItem register, MenuItem login, MenuItem logout, MenuItem expiredListing, MenuItem completeListing, MenuItem activeListing){
if(action=="login"){
register.setVisible(false);
login.setVisible(false);
logout.setVisible(true);
completeListing.setVisible(true);
activeListing.setVisible(true);
expiredListing.setVisible(true);
} else {
register.setVisible(true);
login.setVisible(true);
logout.setVisible(false);
completeListing.setVisible(false);
activeListing.setVisible(false);
expiredListing.setVisible(false);
}
}
private void getMenuItems(NavigationView nv){
register = nv.getMenu().getItem(0);
login = nv.getMenu().getItem(1);
logout = nv.getMenu().getItem(2);
activeListing = nv.getMenu().getItem(3);
completeListing = nv.getMenu().getItem(4);
expiredListing = nv.getMenu().getItem(5);
}
}
I cannot seem to workout why changing the layout is breaking the ActionBar menu options, any help would be appreciated.
Edit:
Changing the <ScrollView> element to <LinearLayout> seems to solve it but I need a ScrollView. The ScrollView seems to overlap the ActionBar and is on the top.
Try setting android:layout_height on the ScrollView to "match_parent" instead of "wrap_content"
so I know there are a few topics around here that ask about this but none seemed to be the cause of my issue. I have an ActionBarActivity that is going to be switching between a few different fragments, but I'm having a problem getting one of the fragments to show up. The activity does show a fragment when it is first loaded and does that fine. Here is the code that is setting up the initial fragment with the method to switch between fragments that I'm using.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("");
if (savedInstanceState == null) navigateTo(START_SCREEN);
}
public void navigateTo(int sectionNumber, Serializable objectParam) {
Fragment fragment = null;
switch (sectionNumber) {
case START_SCREEN:
fragment = createStartScreenFragment(); //returns an instance of the class for this fragment
break;
case SCREEN_TWO:
fragment = createSecondScreenFragment(); //returns an instance of the class for this fragment
break;
}
if (fragment == null) return;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction trans = fm.beginTransaction();
trans.add(R.id.activity_container, fragment, fragment.getTag());
trans.commit();
trans.show(fragment);
}
activity_containers.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
The first fragment that loads successfuly
<GridLayout
android:id="#+id/fragment_start_screen"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android.Activity">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
/>
...
</GridLayout>
And here is the fragment xml that isn't showing up
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
And here is the misbehaving fragments relevant code:
public class SecondFragment extends Fragment {
public final static int SECTION_NUMBER = 1;
private String mTag = "TAG";
private ParentActivity parentActivity;
public SecondFragment() {
}
public static fragment newInstance() {
SecondFragment fragment = new SecondFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentActivity = (ParentActivity) getActivity();
View rootView = inflater.inflate(R.layout.fragment_second_fragment, container, false);
ListView list = (ListView) rootView.findViewById(R.id.list);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
The biggest problem I'm having here is that there is no error message shown. The text view in the first fragment is supposed to trigger the second fragment to show up on the screen. This used to work when I had that fragment as a DialogFragment and just called .show() on an instance of it. I need it to be a regular fragment now and it doesn't show up. There's no error message that I can see, though debugging it does show it running through all of my code successfully and it looks like its properly inflating the view.
So what could I be missing here that is preventing the fragment from displaying?
Your layout
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
Should be within a ViewGroup
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:cacheColorHint="#00000000"
android:fastScrollEnabled="true"
android:padding="2dp">
</ListView>
</LinearLayout>
And you should return rootView in onCreateView().
Also, you might need to use replace method of Fragment Manager to replace one fragment with another, instead of add.