I have a fragment that is half image and then half text.
Trying to assign the ImageView and the TextView but it says:
Might give null
and when I run the app it does not run.
I included the Java and XML files for fragment and included the mainActivity java.
Fragment code:
import android.media.Image;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import android.view.View;
public class headercode extends Fragment implements Runnable{
ImageView image;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getView().findViewById(R.id.imageView ) != null)
{
image = (ImageView)getView().findViewById(R.id.imageView);
}
return inflater.inflate(R.layout.frag, container, false);
}
public void run(){
text.setText("Test");
}
}
Layout XML:
<?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:layout_height="match_parent"
android:background="#692f2f">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="269dp"
android:id="#+id/text"/>
</LinearLayout>
MainActivity code:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.widget.FrameLayout;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (findViewById(R.id.fragment) != null){
headercode header = new headercode();
getSupportFragmentManager().beginTransaction().add(R.id.fragment,header).commit();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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, menu);//This is the setting top right
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Technology) {
} else if (id == R.id.Opinion) {
} else if (id == R.id.travel) {
} else if (id == R.id.politics) {
}else if(id == R.id.Home){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
For fragment you should inflate first your xml in the onCreateView method, you get your view and you can find your corresponding ImageView:
View myView = inflater.inflate(R.layout.frag, container, false);
ImageView myImage = (ImageView) myView.findViewById(R.layout.my_image);
return myView;
In the xml you should add an id to the iamgeView in order to get it:
<ImageView
android:id="#+id/my_image"
android:layout_width="match_parent"
android:layout_height="300dp" />
Trying to assign the ImageView and the textView but it says Might give
null error and when i run the app it does not run.
That's a lint warning informing you that findViewById could return null. If your xml contains the id you are looking for, you don't have anything to worry about.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getView().findViewById(R.id.imageView ) != null)
getView() returns the View the onCreateView returns, therefore you can't use getView() inside onCreateView. Override onViewCreate instead, and its parameter View to perform your findViewById calls
In the fragment you first need to infalte the view and then assing values to its content
Example:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.imageView);
TextView tv = (TextView) rootView.findViewById(R.id.yourTextViewId);
tv.setText("Test");
// Here you will perform all the actions that you want to perform and then in the end return the view like below
return rootView;
}
Related
i have a fragment_home that has 6 buttons and these 6 buttons have there own link(to display something like registration form ) but i have one button from these 6 buttons which is linked to another fragment and has tabbed view with view pager the title of any other fragment will update when i press back but when i entered to the button that links to the tabbed view it makes the toolbar title constant and it won't update there the application unless i exit and open again
for more information i have added some photos with description below
shortly
when application Starts
first image
when i clicked users
second image
when i click back
third image
it updates the title correctly , when i click register own
fourth image
it updates correctly again but now when i press back
last image
it doesnt update the title
main navigation class
package com.example.arada_tech.myapplication;
import android.nfc.Tag;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Navi extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment1;
DrawerLayout drawer;
Tag tag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Displayfragment(R.id.nav_home);
}
boolean doubleBackToExitPressedOnce=false;
// #Override
// public void onBackPressed() {
//
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// if (drawer.isDrawerOpen(GravityCompat.START)) {
// drawer.closeDrawer(GravityCompat.START);
//
// } else {
// if (getFragmentManager().getBackStackEntryCount() > 1) {
// getFragmentManager().popBackStack();
// } else if (!doubleBackToExitPressedOnce) {
// this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();
// new Handler().postDelayed(new Runnable() {
// #Override
// public void run() {
// doubleBackToExitPressedOnce = false;
// }
// }, 2000);
// }
// else {
// System.exit(1);
//// super.onBackPressed();
// }
//
// }
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navi, 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;
}
return super.onOptionsItemSelected(item);
}
private void Displayfragment(int id)
{
Fragment fragment=null;
switch(id) {
case R.id.nav_home:
fragment = new Fragment_Home();
break;
case R.id.nav_addbirr:
// fragment = new Fragment_addbirr();
break;
case R.id.nav_adduser:
fragment = new Fragment_addusers();
break;
case R.id.nav_followorders:
// fragment = new Fragment_followorders();
break;
case R.id.nav_Deleteusers:
// fragment = new Fragment_deleteusers();
break;
case R.id.nav_setings:
// fragment = new Fragment_settings();
Intent tin=new Intent(getApplicationContext(),Menus.class);
startActivity(tin);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
fragment1=fragmentManager.findFragmentById(R.id.nav_home);
ft.replace(R.id.myframelayout,fragment);
// ft.addToBackStack(fragment.getClass().getName());
ft.addToBackStack(fragment.getClass().getName());
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Displayfragment(item.getItemId());
return true;
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
my Fragment_home
package com.example.arada_tech.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Fragment_Home extends Fragment implements View.OnClickListener {
CardView im,in,du,ro;
Fragment fragment=null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("home");
return inflater.inflate(R.layout.mukera,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
im= (CardView) view.findViewById(R.id.card_user);
ro= (CardView) view.findViewById(R.id.card_registerown);
im.setOnClickListener(this);
ro.setOnClickListener(this);
in= (CardView) view.findViewById(R.id.card_order);
in.setOnClickListener(this);
du= (CardView) view.findViewById(R.id.card_deleteuser);
du.setOnClickListener(this);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onClick(View v) {
if(v==im){
fragment = new Fragment_addusers();
FragManager();
}
else if (v==in)
{
// fragment = new Fragment_followorders();
FragManager();
}
else if (v==du)
{
// fragment = new Fragment_deleteusers();
FragManager();
}
else if (v==ro)
{
fragment = new Fragment_registerown();
FragManager();
}
}
public void FragManager()
{
if(fragment!=null)
{
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
ft.replace(R.id.myframelayout,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
}
and my registerown fragment
package com.example.arada_tech.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_registerown extends Fragment {
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("register Own");
setHasOptionsMenu(true);
return inflater.inflate(R.layout.mainslide,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("View"));
tabLayout.addTab(tabLayout.newTab().setText("Create"));
tabLayout.addTab(tabLayout.newTab().setText("Edit"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
final ViewAdapter adapter = new ViewAdapter(((FragmentActivity) getContext()).getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// super.onViewCreated(view, savedInstanceState);
}
for any help thanks in advance
you just need to debug and check
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
method is call or not on the back event of register own fragment.you are not mentions the code line where you called setActionBarTitle() method in the code.
It works when i delete the first two lines of code in registerown_fragment in onviewcreated method Thank you for your help
I am making an android app which has a navigation drawer with fragments being loaded on navigation items.
One of the fragment is containing two tabs which is loading another two fragments via ViewPager.
Everything is working fine as expectations but the problem comes when I select another navigation item from drawer.
One of the tab has options menu but when I go to another fragment and comes back to the earlier, then options menu gets duplicated.
Class LunchTabsFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.*;
public class LunchTabsFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lunch_tabs, container, false);
//Setting tabs layout
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("Menu"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
//Setting pages to be loaded with fragments
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setAdapter(new LunchTabsPagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
}
Class LunchTabsPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class LunchTabsPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public LunchTabsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
LunchMenuFragment tab1 = new LunchMenuFragment();
return tab1;
case 1:
LunchHistoryFragment tab2 = new LunchHistoryFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Class MainActivity
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.*;
import android.view.Menu;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public static final int DRAWER_OPEN = R.string.navigation_drawer_open;
public static final int DRAWER_CLOSE = R.string.navigation_drawer_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, DRAWER_OPEN, DRAWER_CLOSE);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
navigationView.getMenu().performIdentifierAction(R.id.nav_lunch, 0);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (item.getItemId()) {
case R.id.nav_lunch:
fragment = new LunchTabsFragment();
break;
case R.id.nav_attendance:
fragment = new AttendanceFragment();
break;
case R.id.nav_account:
fragment = new ProfileFragment();
break;
case R.id.nav_logout:
UserSessionManager.getInstance(getApplicationContext()).logout();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Class AttendanceFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.*;
public class AttendanceFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_attendance, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Attendance");
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tabs"/>
</RelativeLayout>
<?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:openDrawer="start">
<include
layout="#layout/app_bar_sliding"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_sliding"
app:menu="#menu/activity_sliding_drawer" />
</android.support.v4.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.gaditek.life.MenuActivity"
tools:showIn="navigation_view">
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Class LunchMenuFragment
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class LunchMenuFragment extends Fragment implements View.OnClickListener {
private ArrayList<LunchMenuItem> lunchMenuItemsArray;
private ListView listItemView;
private LunchMenuAdapter adapter;
private String search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_lunch_menu, container, false);
//Initializing Buttons
Button b = (Button) v.findViewById(R.id.btnReview);
b.setOnClickListener(this);
Button a = (Button) v.findViewById(R.id.btnRefresh);
a.setOnClickListener(this);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onPrepareOptionsMenu(android.view.Menu menu) {
menu.findItem(R.id.action_search).setVisible(true);
super.onPrepareOptionsMenu(menu);
}
}
Had to use this code in each fragment in the way to the navigation action where I don't need the options bar
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(android.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
}
i had problem that my string-array not showing in listview at ListFragment, i didn't get any error, just the data of string-array not display. i create a navigation drawer that show data form another fragment
here my ListFragment
import android.os.Bundle;
import android.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentFood extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_food,container,false);
String[] food = getResources().getStringArray(R.array.food_array);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,food);
setListAdapter(adapter);
return rootView;
}
}
MainActivity.java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends FragmentActivity
implements NavigationView.OnNavigationItemSelectedListener {
String nama;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
Intent intent = getIntent();
nama = intent.getStringExtra("Nama");
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView tvNama = (TextView) headerView.findViewById(R.id.tv_name);
tvNama.setText(nama);
fragmentManager = getFragmentManager();
if (savedInstanceState == null) {
fragment = new FragmentFood();
callFragment(fragment);
}
/*FragmentFood fragmentFood = (FragmentFood) getSupportFragmentManager().findFragmentByTag("fragmentfood");
if (fragmentFood == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frame_content,null,"fragmentfood");
transaction.commit();
}*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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, 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;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
ListFragment listFragment=null;
int id = item.getItemId();
if (id == R.id.nav_food) {
listFragment = new FragmentFood();
callFragment(listFragment);
} else if (id == R.id.nav_dessert) {
} else if (id == R.id.nav_drink) {
/*fragment = new FragmentDrink();
callFragment(fragment);*/
} else if (id == R.id.nav_chartpayment) {
} else if (id == R.id.nav_status) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void callFragment(Fragment fragment) {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.replace(R.id.frame_content, fragment);
fragmentTransaction.commit();
}
}
fragment_food.xml
<?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:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
i dont have any idea to show data in ListFragment at NavigationDrawer
I'm trying to use an unique activity that contain navigation view and their option will open another fragment. Everything is ok, unless the MainFragment is being recreated when back from another fragment (that was opened from the navigation view). I'd like to know how to avoid this because it's loading the list again.
MainActivity:
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.home);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.layout, new MainFragment())
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
}
switch (item.getItemId()) {
case R.id.nav_history:
getSupportFragmentManager().beginTransaction()
.replace(R.id.layout, new Fragment2())
.addToBackStack(null)
.commit();
break;
case R.id.nav_settings:
break;
case R.id.nav_logout:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Main Fragment:
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import br.com.example.adapters.ScheduledServicesAdapter;
import br.com.example.entities.ScheduledService;
public class MainFragment extends Fragment {
private final class ScheduleServiceTask extends AsyncTask<Void, Void, List<ScheduledService>> {
#Override
protected List<ScheduledService> doInBackground(Void... params) {
mList = new ArrayList<>();
mList.add(new ScheduledService(new Date(), 250.50, 0));
mList.add(new ScheduledService(new Date(), 50.75, 0));
return mList;
}
#Override
protected void onPostExecute(List<ScheduledService> scheduledServices) {
super.onPostExecute(scheduledServices);
setData(scheduledServices);
}
}
private RecyclerView mRecyclerView;
private ScheduledServicesAdapter mAdapter;
private List<ScheduledService> mList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreateView(inflater, parent, savedInstanceState);
return inflater.inflate(R.layout.content_main, parent, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(),
linearLayoutManager.getOrientation());
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.addItemDecoration(dividerItemDecoration);
new ScheduleServiceTask().execute();
}
private void setData(List<ScheduledService> list) {
ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
if (!list.isEmpty()) {
mAdapter = new ScheduledServicesAdapter(list);
mRecyclerView.setAdapter(mAdapter);
} else {
TextView emptyText = (TextView) getActivity().findViewById(R.id.empty_text);
emptyText.setVisibility(View.VISIBLE);
}
}
}
Fragment 2 has a hello world text view for test purpose.
When you put your MainFragment to BackStack (means that the view
of this fragment is not visible because Fragment2 take the
screen), all the views which belong to it will be destroyed.
Then when you back to MainFragment from another fragment, view of
MainFragment will be re-created. That mean onCreateView and onViewCreated will be
called again.
In your case, I suggest:
Move new ScheduleServiceTask().execute(); to onCreate or to
another method (example: requestGetData())
Init mAdapter and set adapter for mRecyclerView in onViewCreated()
On setData() method, all you need is re-set data for mAdapter and call notifyDatasetChanged() function.
#Douglas Fomaro, Better you can move your data(mList) outside fragment. Maintain DataManager Class that hold all your list data value.
my problem is that as soon as i call a fragment in my main layout, the fragment is called in the frame, but after that, the onitemclick listener stops working. what is that i missed ?
the main.java
import java.util.Locale;
import android.annotation.TargetApi;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Action bar on item click events
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
TextView text = (TextView) arg1.findViewById(android.R.id.text1);
String MenuName = text.getText().toString();
Log.d("Click", MenuName);
if(position == 0){
Log.d("Click","Home Clicked");
// update the main content by replacing fragments
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
fragmentTransaction.commit();
}
else if(position == 1){
Log.d("Click","News Clicked 2");
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
This is the main.xml
<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"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
This is the menugragment which calls the layout.
public class MenuFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.sports, container, false);
}
}
Now, as it is replaced in the frame in main (when the position is 0, the fragment is called),after that if 1 is called, the onitemclicklistener does not work. why is that ?
Thank you
replace
fragmentTransaction.replace(R.id.drawer_layout, fragment, String.valueOf(position));
to
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
You should replace the content_frame not the drawer_layout