How to load a fragment view in a tab - android-fragments

I am trying to create tabs inside a fragment. I manage to create tab inside the fragment, but now I want to load different fragment for each tab (fragment1.class and fragment2.class).
Can anybody please suggest how can i load each fragment to their respective tabs?
Below is my main fragment that is holding the tabs.
Thanks a lot!
public class BusFragment extends Fragment {
private TabHost mTabHost;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bus, container, false);
mTabHost = (TabHost) rootView.findViewById(R.id.tabHost);
mTabHost.setup();
TabHost.TabSpec spec = mTabHost.newTabSpec("tag");
spec.setIndicator("Fragment1");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag1");
spec.setIndicator("Fragment2");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
spec = mTabHost.newTabSpec("tag2");
spec.setIndicator("Fragment3");
spec.setContent(new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
// TODO Auto-generated method stub
return (new AnalogClock(getActivity()));
}
});
mTabHost.addTab(spec);
return rootView;
}
}

Hello If you want to load the fragment inside the fragment android provide the Child Fragment Manager instead of ordinary fragment manager. I had the same issue I had the fragment inside that tab when click on tab want to load the different fragments. see the below steps hope will help you.
Step 1. See I have StatisticsFragment with it layout fragment_statistics.
public class StatisticsFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_statistics,container, false);
mTabHost = (FragmentTabHost) rootView.findViewById(R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(),R.id.tabFrameLayout);
mTabHost.addTab(mTabHost.newTabSpec("WEEK").setIndicator(buildTabLayout(EnumStatistics.WEEKLY)),WeekFragment_.class, null);
mTabHost.addTab(mTabHost.newTabSpec("ALL").setIndicator(buildTabLayout(EnumStatistics.ALL)),DetailedFragment_.class, null);
mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new WeekTabClick());
mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new AllTabClick());
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
private View buildTabLayout(EnumStatistics enumStatistics) {
View tab;
if (enumStatistics == EnumStatistics.WEEKLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_week_layout, null);
} else if (enumStatistics == EnumStatistics.MONTHLY) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_month_layout, null);
} else if (enumStatistics == EnumStatistics.YEAR) {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_year_layout, null);
} else {
tab = getActivity().getLayoutInflater().inflate(R.layout.tab_detailed_layout, null);
}
return tab;
}
public class WeekTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(0);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.tabFrameLayout, WeekFragment_.instantiate(getActivity(), WeekFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
public class AllTabClick implements View.OnClickListener {
#Override
public void onClick(View v) {
mTabHost.getTabWidget().focusCurrentTab(1);
FragmentTransaction ft = getChildFragmentManager()
.beginTransaction();
ft.replace(R.id.tabFrameLayout, DetailedFragment_.instantiate(
getActivity(), DetailedFragment_.class.getName()));
ft.addToBackStack(null);
ft.commit();
}
}
}
In above buildTabLayout function intent to build the custom layout of tab widget you can put simple text or image that you want to show inside the tab widget.
Steps 2. fragment_statistics.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:relaxis="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/croutonview"
android:gravity="center" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
/>
<FrameLayout
android:id="#+id/tabFrameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</RelativeLayout>
As you see in the above inside the layout tabFrameLayout we load the all child fragment Programmaticly.
Let me know if you have any question and doubt. thank you

Related

Android how to call Navigation Drawer from fragment

In my fragment I have material search bar with navigation button(humbugger).
How can I call Navigation Drawer which is in main activity with that humbugger button in my fragment
Do not get how to handle it inside DictionaryFragment
MainActivity:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawer,
R.string.nav_open_drawer,
R.string.nav_close_drawer){
};
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
DictionaryFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
materialSearchBar = (MaterialSearchBar) RootView.findViewById(R.id.search_bar);
...
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onButtonClicked(int buttonCode) {
//***HOW TO HANDLE IT HERE?***
//switch (buttonCode) {
// case MaterialSearchBar.BUTTON_NAVIGATION:
// drawer.openDrawer(Gravity.START);
// break;}
}
});
//return RootView;
}
layout
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/searchBarDividerColor"
tools:context="com.hfad.catchat.DictionaryFragment">
<com.mancj.materialsearchbar.MaterialSearchBar
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:mt_hint="Search"
app:mt_navIconEnabled="true"
app:mt_speechMode="false" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is what you can try where you want to toggle navigation drawer in your fragment, this way you will have to write a method in activity to do whatever you want to do from your fragment, be sure it is a public method:
((MainActivity)getContext()).toggleDrawer();
in your MainActivity:
public void toggleDrawer(){
//do your stuff
}
Other way is callback aka interface (the preferred one), pass that as a parameter in fragment's constructor and consume that where you want to change drawer's state. Like inside your activity:
Callback callback = new Callback(){
#Override
public void onDrawerStateChanged(){
//do your stuff
}};
new DictionaryFragment(callback);
And inside your fragment you will have to write a constructor to accept that callback and save in a local variable :
public DictionaryFragment() {
}
#SuppressLint("ValidFragment")
public DictionaryFragment(Callback callback) {
this.callback = callback;
}
And use it like :
callback.onDrawerStateChanged();
You can also pass parameters to MainActivity both ways.

Working with fragments - findViewById returns NULL on Button in Android

I've started dealing with Fragments in Android. I created Activity with NavigationView which has 3 items and worked with 3 simple fragments till now. NavigationHeader has 2 buttons - 1 starts LoginActivity and 2nd RegisterActivity. I remind that everything till niw worked fine. Today I've tried to create RecyclerView inside one of the fragments. Now when I try to run app, findViewById applied to those 2 NavigationHeader buttons returns NULL. I have no idea why.
Here is HomeActivity:
public class HomeActivity extends AppCompatActivity {
private static final String FRAGMENT_POSITION = "fragment_position"; // Fragment Position
private DrawerLayout mDrawerLayout; // NavigationDrawer Layout
private NavigationView nvDrawer; // NavigationView
private CoordinatorLayout homeCoordinatorLayout; // Coordinator Layout For Snackbar
private Toolbar toolbar; // Application Toolbar
private TextView navHeaderNamePlusSurname; // Name And Surname Navigation Header Text
private TextView navHeaderEmail; // E-mail Navigation Header Text
AppCompatButton navHeaderButtonLogin; // Login/Logout Button
AppCompatButton navHeaderButtonRegister; // Register Button
private ActionBarDrawerToggle mDrawerToggle; // ActionBar Drawer Toggle
private SQLiteHandler db; // SQLite Database Helper Class
private SessionManager session; // Session Manager
private int lastShownFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Setting Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Setting Up DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = setupDrawerToggle();
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Navigation Header Logout Button
navHeaderButtonLogin = (AppCompatButton) findViewById(R.id.nav_header_btn_log_in_out);
navHeaderButtonRegister = (AppCompatButton) findViewById(R.id.nav_header_btn_register);
Log.d("czy_null", "navHeaderButtonLogin: " + navHeaderButtonLogin + ", navHeaderButtonRegister: " + navHeaderButtonRegister);
// Name, Surname And E-mail Texts
navHeaderNamePlusSurname = (TextView) findViewById(R.id.nav_header_name_plus_surname);
navHeaderEmail = (TextView) findViewById(R.id.nav_header_email);
// SQLite Database Handler
db = new SQLiteHandler(getApplicationContext());
// Session Manager
session = new SessionManager(getApplicationContext());
// Navigation Drawer
nvDrawer = (NavigationView) findViewById(R.id.navigation_view);
// Checking If User Is Logged In
if (!session.isLoggedIn()) {
hideNavigationViewGroup(nvDrawer); // Hiding NavigationView Group Depending
// If Not Logged
} else {
navHeaderButtonLogin.setText(getText(R.string.home_btn_log_out));
navHeaderButtonRegister.setVisibility(View.INVISIBLE);
// Fetching User Details From SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get(SQLiteHandler.KEY_NAME);
String surname = user.get(SQLiteHandler.KEY_SURNAME);
String email = user.get(SQLiteHandler.KEY_EMAIL);
// Setting Navigation Header Texts
String nameSurname = name + " " + surname;
navHeaderNamePlusSurname.setText(nameSurname);
navHeaderEmail.setText(email);
}
// Setting Up CoordinatorLayout
homeCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.home_coordinator_layout);
// Setting Listener To NavigationView
setupDrawerContent(nvDrawer);
// Setting Starting Fragment
if (savedInstanceState == null) {
setStartingFragment();
} else {
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Applying Login/Logout Button Listener
setLoginButtonListener();
// Applying Register Button Listener
setRegisterButtonListener();
}
// Listener To Login/Register Button
private void setLoginButtonListener() {
navHeaderButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!session.isLoggedIn()) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
} else {
mDrawerLayout.closeDrawers();
logoutUser();
navHeaderNamePlusSurname.setText(getString(R.string.nav_header_name_surname));
navHeaderEmail.setText(getString(R.string.nav_header_email));
hideNavigationViewGroup(nvDrawer);
navHeaderButtonLogin.setText(getString(R.string.home_btn_log_in));
navHeaderButtonRegister.setVisibility(View.VISIBLE);
showSnackbarInfo(getString(R.string.inf_logout_success),
R.color.snackbar_success_msg);
}
}
});
}
// Listener To Register Button
private void setRegisterButtonListener() {
navHeaderButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
}
// Logging Out The User
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
}
// Setting Up DrawerToggle
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close);
}
// Setting Up Drawer Content
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
// Replace Existing Fragment With a New One
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_top20_recipes: {
fragmentClass = Top20RecipesFragment.class;
lastShownFragment = 0;
break;
}
case R.id.nav_kitchen_type: {
fragmentClass = KitchenTypeFragment.class;
lastShownFragment = 1;
break;
}
case R.id.nav_meal_type: {
fragmentClass = MealTypeFragment.class;
lastShownFragment = 2;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
mDrawerLayout.closeDrawers(); // Close The Drawer
}
// Function Setting First Fragment
private void setStartingFragment() {
Fragment fragment = null;
Class fragmentClass = Top20RecipesFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = 0;
MenuItem menuItem = nvDrawer.getMenu().getItem(0);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
}
// Saving Fragment Title State
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(FRAGMENT_POSITION, lastShownFragment);
}
// Restoring Fragment Title States
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Restoring Selected Item On Screen Rotation Or App Minimalize
private void restoreOnInstanceState(int lastPosition) {
Fragment fragment = null;
Class fragmentClass = null;
switch (lastShownFragment) {
case 0: {
fragmentClass = Top20RecipesFragment.class;
break;
}
case 1: {
fragmentClass = KitchenTypeFragment.class;
break;
}
case 2: {
fragmentClass = MealTypeFragment.class;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = lastPosition;
MenuItem menuItem = nvDrawer.getMenu().getItem(lastPosition);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Function Hiding Items In NavigationView
private void hideNavigationViewGroup(NavigationView nvDrawer) {
nvDrawer.getMenu().setGroupVisible(R.id.nav_group_logged_user, false);
}
// Function Showing Snakcbar
private void showSnackbarInfo(String info, int textColor) {
Snackbar snackbar = Snackbar.make(homeCoordinatorLayout, info, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView sbText = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
sbText.setTextColor(ContextCompat.getColor(getApplicationContext(), textColor));
snackbar.show();
}
}
Here is my fragment which has to contain RacyclerView:
public class KitchenTypeFragment extends Fragment {
RecyclerView kitchenTypeRecycleView;
private ArrayList<KitchenTypeItem> kitchenTypeItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
kitchenTypeItems = new ArrayList<>();
fillKitchenTypeArray(kitchenTypeItems);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kitchen_type, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
kitchenTypeRecycleView = (RecyclerView) view.findViewById(R.id.kitchen_type_recycle_view);
kitchenTypeRecycleView.setHasFixedSize(true);
kitchenTypeRecycleView.setAdapter(new KitchenTypeAdapter(kitchenTypeItems,
R.layout.kitchen_type_grid_item));
kitchenTypeRecycleView.setLayoutManager(new GridLayoutManager(getContext(), 2));
kitchenTypeRecycleView.setItemAnimator(new DefaultItemAnimator());
}
private void fillKitchenTypeArray( ArrayList<KitchenTypeItem> kitchenTypeItems) {
KitchenTypeItem kitchenItem;
// Currently 8 Kitchen Types
String[] itemNames = getResources().getStringArray(R.array.kitchen_types);
// Filling ArrayList
for(int i = 0; i < itemNames.length; i++) {
kitchenItem = new KitchenTypeItem(itemNames[i], R.drawable.example_kitchen_type);
kitchenTypeItems.add(kitchenItem);
}
}
}
Here is XML from HomeActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity">
<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=".SignUpActivity">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/frame_layout_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
Here is NavigationHeader XML with those 2 buttons:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relative_nav_header"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="#color/primary"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="40dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical">
<!-- Name + Surname, E-mail -->
<LinearLayout
android:id="#+id/nav_lin_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:orientation="vertical">
<!-- Name + Surname Text -->
<TextView
android:id="#+id/nav_header_name_plus_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textSize="17sp"
android:text="#string/nav_header_name_surname" />
<!-- E-mail Adress -->
<TextView
android:id="#+id/nav_header_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/accent"
android:fontFamily="sans-serif"
android:textSize="13sp"
android:text="#string/nav_header_email" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp"
android:gravity="center|left"
android:layout_below="#+id/nav_lin_layout">
<!-- Login/Logut Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_log_in_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_login_color"
android:textColor="#color/text_icons"
android:stateListAnimator="#null"
android:text="#string/btn_log_in" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_register_color"
android:stateListAnimator="#null"
android:textColor="#color/text_icons"
android:text="#string/btn_sign_up" />
</LinearLayout>
</RelativeLayout>
And here is finally XML from Fragment:
<FrameLayout
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"
android:id="#+id/kitchen_type_fragment"
android:padding="16dp"
tools:context="com.example.nazwamarki.myapplication.fragments.KitchenTypeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/kitchen_type_recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
You should use findViewById on the headerView like this:
navigationView.getHeaderView(0).findViewById()

Rate us In Android fragment

I'm trying to rewrite this project using fragments. I'm replacing activities with fragments.
This is XML file :
'<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Rate Us" />
and this is the Full Source Code java:-
'public class MainActivity extends Activity{
Button rate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rate=(Button)findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse ("market://details?id=APP ID"));
startActivity(intent);
}
});
}}`
what is the java right code for use this in a fragment?
Thanks in advance....
This is how it is done:
public class MainActivity extends Fragment {
Button rate;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
rate = (Button) rootView.findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse ("market://details?id=APP ID"));
startActivity(intent);
}
});
return rootView;
}
There is no need to change anything in the xml file.
Hope this helps :)

Using a progressBar in a listview item

I have this listview and it's coded in a fragment class. When selecting a listview item it goes to another fragment and displays the details . But it takes several seconds to load the data because the data i display is using AsyncTask,so it takes some time to get data from the JSON and display . So i need to use a progressBar when an item is clicked in the listview and it should close when the data is ready to display. How can i do this? I referred several tutorials and tried many of them. But i couldn't accomplish what i'm looking for.Hope some of you can help me.
NewsFragment class
private ListView listView;
private ArrayList<BaseElement> News;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.news_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
listView = (ListView) view.findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
android.support.v4.app.Fragment detail = new NewsDetailFragment();
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, detail).addToBackStack("back").commit();
}
});
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
News = JSONServices.getNewsDescription();
return null;
}
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setNewsDescription(News);
adapter = new LazyAdapter(News, activity,Element.NEWS_LIST.getType());
listView.setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsDetailFragment
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsList layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/listview" >
<ImageView
android:id="#+id/thumb_image"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
/>
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_toRightOf="#+id/thumb_image"
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:textStyle="bold"
android:textSize="20dp" />
<!-- <TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:layout_below="#+id/news_title"
android:textSize="15dp" /> -->
</LinearLayout>
</RelativeLayout>
NewsFragment layout
<?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"
android:background="#color/grey" >
<!-- <GridView
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:layout_margin="5dp"
android:columnWidth="100dp"/> -->
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:dividerHeight="10dp"
android:layout_margin="6dp">
</ListView>
</LinearLayout>
Add ProgressBar to your NewsFragment layout:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="gone" />
Then in onItemClick method change it's visibility to true progressBar.setVisibility(View.VISIBLE) to show it and change it's visibility to false to hide it progressBar.setVisibility(View.GONE) in onPostExecute of AsyncTask.
Ok i got it now. I modified my 2nd fragment like this. When an item in the listview is clicked it goes to my second class.So i added a progressBar to my second class and it worked!
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}

How to transfer variables to a fragment was created using the ActionBarActivity?

The activity is called from another activity delivering a string array, which needs to be displayed in a fragment of the target activity.
MainActivity (string array) -> Result2Activity: Tab1 should display string index0, Tab2 should display string index1 etc.
I followed a similar problem here:
Access Fragment View from Activity's onCreate
My problem is right now that the onActivityCreated method is never called in the Result2Activity.
I am also not sure if this method is the right way to address the fragment:
getSupportFragmentManager().findFragmentByTag("Out1");
What is the best way to achieve that ?
Result2Activity:
public class Result2Activity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
public List<String> fragments = new Vector<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result2_activity);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
Log.d("DEBUG","1: onCreate finished");
}
public void onActivityCreated (Bundle savedInstanceState) {
Log.d("DEBUG","2: onActivityCreated finished");
//super.onActivityCreated(savedInstanceState);
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
//send data to fragment Out1Fragment
Out1Fragment set_out1 =
(Out1Fragment)
getSupportFragmentManager().findFragmentByTag("Out1");
set_out1.settext(message[0]);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragments.add(Out1Fragment.class.getName());
fragments.add(Out2Fragment.class.getName());
fragments.add(Out3Fragment.class.getName());
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Out1Fragment();
break;
case 1:
fragment = new Out2Fragment();
break;
case 2:
fragment = new Out3Fragment();
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.out_section1).toUpperCase(l);
case 1:
return getString(R.string.out_section2).toUpperCase(l);
case 2:
return getString(R.string.out_section3).toUpperCase(l);
}
return null;
}
}
}
Out1Fragment:
public class Out1Fragment extends Fragment {
private static TextView textview;
public Out1Fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.out1_fragment, container,
false);
textview = (TextView) dataView.findViewById(R.id.outPut1);
return dataView;
}
public void settext(String text)
{
textview.setText(text);
}
}
XML Resource:
result2_activity.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dd.testing.finance.Result2Activity" />
out1_fragment.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ScrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:tag="Out1"
tools:context="dd.testing.finance.Result2Activity$Out1Fragment" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/outPut1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:textSize="16sp" />
</LinearLayout>
</ScrollView>
Not really sure if this was the right way, but at least it does exaclty what I needed.
In the Out1Fragment.class added the onActivityCreated method:
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
settext(((Result2Activity)getActivity()).getOutput1());
}
From there calling the added method getOutput1 in the Result2Activity:
public String getOutput1 () {
// retrieve data from MainActivity
Intent intent = getIntent();
String message[] = intent.getStringArrayExtra(MainActivity.OUTPUT);
return message[0];
}

Resources