how to use thread with navigation drawer fragments? - java

Context:
I am new to android. I have created a navigation drawer with fragments. When I run my code the app works but the choreographer says:
** frames skipped, heavy work is done in main thread.
The Problem:
The App became slow when I move to a fragment layout where there is more data. I searched for how to solve this problem and I learned using threads will solve the issue but I am so confused to use it.
Can anyone help me?
The Code:
package com.example.venkatesh.settaiboyz;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public final void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = home_fragment.newInstance(position + 1);
break;
case 1:
fragment = member_fragment.newInstance(position + 1);
break;
case 2:
fragment = photo_fragment.newInstance(position + 1);
break;
case 3:
fragment = event_fragment.newInstance(position + 1);
break;
case 4:
fragment = about_fragment.newInstance(position + 1);
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_layout, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.action_facebook:
Open_facebook();
return true;
case R.id.action_twitter:
Open_Twitter();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Anvar
public void OpenActivityAnvar(View view) {
setContentView(R.layout.anvar);
ImageButton b;
b = (ImageButton) findViewById(R.id.call_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+919841463562"));
startActivity(callIntent);
}
});
b = (ImageButton) findViewById(R.id.sms_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+919841463562");
smsIntent.putExtra("sms_body", "");
startActivity(smsIntent);
}
});
b = (ImageButton) findViewById(R.id.mail_anvar);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);//common intent
intent.setData(Uri.parse("mailto:mailtoanvar8055#gmail.com"));
startActivity(intent);
}
});
}
//Main menu list
public void Open_facebook() {
Uri webpage = Uri.parse("https://www.facebook.com/settaiboyz");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(webIntent);
}
public void Open_Twitter() {
Uri webpage = Uri.parse("https://www.Twitter.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(webIntent);
}
}

Related

actions vs. fragment changes in navigation drawer

So, I followed a tutorial to add a sliding navigation drawer to my app (plus did some tweaking of my own), but I'm a bit confused, possibly because I don't totally grok fragments. Basically I created an overflow menu with Log Out as the only option, so I could test my login system. I want that log out option in my navigation drawer so I can just get rid of that that overflow menu, but I can't figure out what to change so that it logs out instead of just displays the title of the fragment that was clicked on. And while I'm asking basically the same question, if I wanted to create the page that someone is viewing when they click on an option in the navigation drawer, where would I do that? In the respective fragment?
MainActivity.java
package me.paxana.alerta;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import me.paxana.alerta.adapter.SlidingMenuAdapter;
import me.paxana.alerta.fragment.Fragment1;
import me.paxana.alerta.fragment.Fragment2;
import me.paxana.alerta.fragment.Fragment3;
import me.paxana.alerta.model.ItemSlideMenu;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private android.support.v7.app.ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
}
else {
Log.i(TAG, currentUser.getUsername());
}
listViewSliding = (ListView)findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//add item for sliding list
listSliding. add(new ItemSlideMenu(R.drawable.ic_action_settings, "Settings"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, "About"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_logout_black_48dp, "Log Out"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//display icon to open/close slider
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
//handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
//create method replace fragment
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
Fragment3 (I tried adding the logout option to this fragment but to no avail. Still what happens when I click it is the text "Log Out" displays on the screen)
package me.paxana.alerta.fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.parse.ParseUser;
import me.paxana.alerta.LoginActivity;
import me.paxana.alerta.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Fragment3.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Fragment3#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment3 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Fragment3() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Fragment3.
*/
// TODO: Rename and change types and number of parameters
public static Fragment3 newInstance(String param1, String param2) {
Fragment3 fragment = new Fragment3();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParseUser.logOut();
Intent intent = new Intent(Fragment3.this.getActivity(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment3, container, false);
// Inflate the layout for this fragment
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
If I understood what you're looking for, you can log out by clicking the log-out element of the Navigation Drawer List:
Try this:
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == logOutIndex) { //You can do this if you know the position of the logOut button, e.g it's always at the end of the ListVIew
ParseUser.logOut();
navigateToLogin();
}
}
});
I hope that it works:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
//ParseUser.logOut();
//navigateToLogin();
//If you the latest activity was te LoginActivity it goues to the LoginActivity
finish();
}
return super.onOptionsItemSelected(item);
}
Or if you is trying to do it from the drawer, replace you fragment3 by this:
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
//fragment = new Fragment3();
//If you the latest activity was te LoginActivity it goues to the LoginActivity
finish();
break;
default:
fragment = new Fragment1();
break;
}
Its hard to explain because you have to do so much to get it work.
The first idea I have is that you paste your code to log out into the switch case in the MainActivity.java:
private void replaceFragment(int pos) {
android.support.v4.app.Fragment fragment = null;
switch (pos) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
ParseUser.logOut();
Intent intent = new Intent(Fragment3.this.getActivity(),LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
fragment = new Fragment3();
break;
default:
fragment = new Fragment1();
break;
}
if(null != fragment) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
...
I hope I understood you right but this has to fix the problem and if you now click on the 3rd fragment your logout has to be made.
If I am wrong write back soon and I will look for another solution ;)

How to change the ActionBar title from the fragment class in Android Studio?

please help me..
i use the builtin Navigation Drawer Activity in Android Studio..
what i want is to change the Bar title from fragment..
here is my code
MainActivity.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectconnection = new Seocnd(this);
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new AccountFragment();
break;
}
if (fragment == null) {
fragment = new HomeFragment();
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_home);
break;
case 2:
mTitle = getString(R.string.title_account);
break;
}
}
public void restoreActionBar () {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled( true );
actionBar.setTitle( mTitle );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
package com.example.administrator.mosbeau;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_home),
getString(R.string.title_account),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// 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
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I want to change the Bar Title in every fragment displayed like
HomeFragment.java
package com.example.administrator.mosbeau;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Administrator on 9/7/2015.
*/
public class HomeFragment extends Fragment {
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homelayout, container, false);
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
}
EDIT: PLEASE HELP ME..
Based on your code you don't need to change action bar title from fragment
you can change inside your switch case
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String title = "";
switch (position) {
case 0:
fragment = new HomeFragment();
title="Home";
break;
case 1:
fragment = new AccountFragment();
title="Accounts";
break;
}
if (fragment == null) {
fragment = new HomeFragment();
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
getSupportActionBar().setTitle(title);
}
Even if you want to change actionbar from fragment use interface
Create a interface inside fragment
Implement the Interface in Activity
When you want to change actionbar using callback call the interface function in Activity
add + 1 to onSectionAttached
public void onSectionAttached(int number) {
switch (number + 1) { // add +1 here
case 1:
mTitle = getString(R.string.title_home);
break;
case 2:
mTitle = getString(R.string.title_account);
break;
}
}

My PDF is not opening, and no error shows in locgcat

I am trying to open a pdf that I have saved to my download folder. No error in logcat is showing and when i click the button, nothing happens.
View view;
public void tob(View view) {
File file = new File("/sdcard/Download/mpsampletob.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
FYI, 'tob' is the name of the button, 'mpsampletob' is the name of the document.
logcat:
12-18 03:24:30.978 24992-24992/com.example.paul.navigationdrawer I/View﹕ Touch down dispatch to android.widget.Button{4284a098 VFED..C. ........ 169,731-486,827 #7f09005f app:id/tob}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=142.52289, y[0]=40.097534, Xw[0]=28.0, Yw[0]=28.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=198118232, downTime=198118232, deviceId=3, source=0x1002 }
12-18 03:24:31.142 24992-24992/com.example.paul.navigationdrawer I/View﹕ Touch up dispatch to android.widget.Button{4284a098 VFED..C. ...p.... 169,731-486,827 #7f09005f app:id/tob}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=142.52289, y[0]=40.097534, Xw[0]=28.0, Yw[0]=28.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=198118398, downTime=198118232, deviceId=3, source=0x1002 }
12-18 03:24:31.156 24992-24992/com.example.paul.navigationdrawer D/OpenGLRenderer﹕ prepareDirty (0.00, 0.00, 720.00, 1280.00) opaque 1 <0x60085008>
12-18 03:24:31.157 24992-24992/com.example.paul.navigationdrawer D/OpenGLRenderer﹕ finish <0x60085008>
12-18 03:24:31.159 24992-24992/com.example.paul.navigationdrawer V/Provider/Settings﹕ from settings cache , name = sound_effects_enabled , value = 0
12-18 03:24:31.234 24992-24992/com.example.paul.navigationdrawer D/OpenGLRenderer﹕ prepareDirty (0.00, 0.00, 720.00, 1280.00) opaque 1 <0x60085008>
12-18 03:24:31.235 24992-24992/com.example.paul.navigationdrawer D/OpenGLRenderer﹕ finish <0x60085008>
If you want to know what I am trying to do...mainactivity.java
package com.example.paul.navigationdrawer;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.protocol.HTTP;
import java.io.File;
import java.util.List;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
private Button calloutsideuae;
private Button callinsideuae;
private Button emailamity;
private Button tob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
android.app.Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new HealthFragment();
break;
case 2:
fragment = new PolicyFragment();
break;
case 3:
fragment = new ProviderFragment();
break;
case 4:
fragment = new ContactFragment();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container,fragment).commit();}
}
public void onSectionAttached(int number) {
switch (number) {
case 0:
mTitle = getString(R.string.title_section1);
break;
case 1:
mTitle = getString(R.string.title_section2);
break;
case 2:
mTitle = getString(R.string.title_section3);
break;
case 3:
mTitle = getString(R.string.title_section4);
break;
case 4:
mTitle = getString(R.string.title_section5);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
public class HomeFragment extends android.app.Fragment {
private HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
}
public class HealthFragment extends android.app.Fragment {
public HealthFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_health, container, false);
return view;
}
}
public class PolicyFragment extends android.app.Fragment {
public PolicyFragment() {
}
private Button tob;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_policy, container, false);
return view;
}
}
public class ProviderFragment extends android.app.Fragment {
public ProviderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_provider, container, false);
return view;
}
}
public class ContactFragment extends android.app.Fragment {
public ContactFragment() {
}
private Button calloutsideuae;
private Button callinsideuae;
private Button emailamity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contact, container, false);
return rootView;
}
}
View view;
//OPEN / DOWNLOAD THE TOB********************************************************
public void tob(View view) {
File file = new File("/sdcard/Download/mpsampletob.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
//CONTACT US FRAGMENT BUTTON ACTIONS******************************************************
public void callinsideuae(View view) {
//Build the intent
Uri number = Uri.parse("tel:+971569576839");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
//Resolves?
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(callIntent, 0);
boolean isIntentSafe = activities.size() > 0;
//Start if safe to do so
if (isIntentSafe) {
startActivity(callIntent);
}
}
public void calloutsideuae(View view){
//Build the intent
Uri number = Uri.parse("tel:+971569576839");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
//Resolves?
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(callIntent, 0);
boolean isIntentSafe = activities.size() > 0;
//Start if safe to do so
if (isIntentSafe) {
startActivity(callIntent);
}
}
public void emailamity(View view){
//Build the intent
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// The intent does not have a URI, so declare the "text/plain" MIME type
emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"paul.ali#amity.ae"}); // recipients
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));
// You can also attach multiple items by passing an ArrayList of Uris
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(emailIntent, 0);
boolean isIntentSafe = activities.size() > 0;
//Start if safe to do so
if (isIntentSafe) {
startActivity(emailIntent);
}
}
}
SOLUTION:
public void tob(View view) {
Intent i=new Intent(Intent.ACTION_VIEW);
File file = new File("/sdcard/Download/mpsampletob.pdf");
i.setDataAndType(Uri.fromFile(file), "application/pdf");
startActivity(i);
}
I have solved this, but appreciate the help!
public void tob(View view) {
Intent i=new Intent(Intent.ACTION_VIEW);
File file = new File("/sdcard/Download/mpsampletob.pdf");
i.setDataAndType(Uri.fromFile(file), "application/pdf");
startActivity(i);
}

Access the variable of a fragment from a ActionBarActivity

I used the example that incorporates Android Studio to make an example of a NavigationDrawer in Android. I made some small modifications to the code to perform various operations from the main activity.
package ugr.mohabb.navigationdrawerexample;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**dsf* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private int sectionSelected;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
this.sectionSelected=position;
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment;
switch(position){
case 0:
fragment=new PlaceholderFragment("Section 1");
// I want to acces to variable Example, I try:
break;
case 1:
fragment=new PlaceholderFragment("Section 2");
break;
case 2:
fragment=new PlaceholderFragment( "Section 3");
break;
default:
fragment=new PlaceholderFragment("Default");
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private String Example;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment("Default");
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment( String Example) {
this.Example=Example;
}
public String getExample() {
return Example;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
I modified the Fragment to incorporate a String as an argument to the constructor.
private String Example;
public PlaceholderFragment( String Example) {
this.Example=Example;
}
In the ActivityMain I added a switch to different operations :
#Override
public void onNavigationDrawerItemSelected(int position) {
this.sectionSelected=position;
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment;
switch(position){
case 0:
fragment=new PlaceholderFragment("Section 1");
// I want to acces to variable Example??
break;
case 1:
fragment=new PlaceholderFragment("Section 2");
break;
case 2:
fragment=new PlaceholderFragment( "Section 3");
break;
default:
fragment=new PlaceholderFragment("Default");
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
My question is, how do i could access to the methods and variables of the Fragment extends class from the activity?
Thanks,
When user selects a list item from navigation drawer, we need to display respected view in the main view. This can be done by adding a list item click listener and loading respected fragment view in the call back event.
Sample code:
public class MainActivity extends Activity {
..
..
#Override
protected void onCreate(Bundle savedInstanceState) {
..
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
For more details, please refer to here.
In your fragment, declare the interface...
public interface OnDataPass {
public void onDataPass(String data);
}
Then, connect the containing class implementation of the interface to the fragment in the onAttach method, like so:
OnDataPass dataPasser;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
dataPasser = (OnDataPass) a;
}
Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:
public void passData(String data) {
dataPasser.onDataPass(data);
}
Finally, in your containing activity which implements OnDataPass...
#Override
public void onDataPass(String data) {
Log.d("LOG","hello " + data); // or whatever
}

Android:Painting in FragmentClass

I am using navigationdrawer in an activity.If I click any of the item in the navigation drawer
in default with some color it should allow us to paint some thing.But I tried for a long time i was unable to do it.Kindly hep as soon as possible.Below is my code which i am using.
Painting.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
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.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Painting extends Activity {
private ListView mdrawerlist;
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mdrawertitle;
private CharSequence mtitle;
private String[] mfragmenttitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_painting);
mtitle = mdrawertitle = getTitle();
mfragmenttitles = getResources().getStringArray(R.array.widgets);
mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerlist = (ListView) findViewById(R.id.left_drawer);
mdrawerlist.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mfragmenttitles));
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mdrawerlist.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mdrawerlayout,
R.drawable.ic_launcher, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mtitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mdrawertitle);
invalidateOptionsMenu();
}
};
mdrawerlayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.painting, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean draweropen = mdrawerlayout.isDrawerOpen(mdrawerlist);
menu.findItem(R.id.action_settings).setVisible(!draweropen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
if (mdrawerlayout.isDrawerOpen(mdrawerlist)) {
mdrawerlayout.closeDrawer(mdrawerlist);
} else {
mdrawerlayout.openDrawer(mdrawerlist);
}
mdrawerlayout.openDrawer(mdrawerlist);
/*
* Toast.makeText(getApplicationContext(), "Options Selected",
* Toast.LENGTH_LONG).show();
*/
return true;
case android.R.id.home:
startActivity(new Intent(Painting.this, MainActivity.class));
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
// args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragment = new Fragment1();
Toast.makeText(getApplicationContext(), "Camera Selected",
Toast.LENGTH_LONG).show();
break;
case 1:
fragment = new Fragment2();
Toast.makeText(getApplicationContext(), "Color Selected",
Toast.LENGTH_LONG).show();
break;
case 2:
/*
* PaintFragment fragment1; fragment1 = new PaintFragment();
*/
PaintFragment fragment1 = new PaintFragment();
Toast.makeText(getApplicationContext(), "Paint Selected",
Toast.LENGTH_LONG).show();
break;
case 3:
fragment = new Fragment4();
Toast.makeText(getApplicationContext(), "Save selected",
Toast.LENGTH_LONG).show();
break;
case 4:
fragment = new Fragment5();
Toast.makeText(getApplicationContext(), "Share Selected",
Toast.LENGTH_LONG).show();
break;
case 5:
fragment = new Fragment6();
Toast.makeText(getApplicationContext(), "ArtBy Selected",
Toast.LENGTH_LONG).show();
break;
case 6:
fragment = new Fragment7();
Toast.makeText(getApplicationContext(), "Refresh Selected",
Toast.LENGTH_LONG).show();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mdrawerlist.setItemChecked(position, true);
setTitle(mfragmenttitles[position]);
mdrawerlayout.closeDrawer(mdrawerlist);
}
#Override
public void setTitle(CharSequence title) {
mtitle = title;
getActionBar().setTitle(mtitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
PainitngFragment.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PaintFragment extends Activity {
/*private static int displayWidth = 0;
private static int displayHeight = 0;
*/
/*
* #Override public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* //setContentView(R.layout.activity_fragment3); //setContentView(new
* MyView(this));
*
*
* }
*/
/*public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrushView view=new BrushView(this);
setContentView(view);
addContentView(view.btnEraseAll, view.params);
/*
* View view = inflater.inflate(R.layout.activity_fragment3, container,
* false);
*/
// getActivity();
/*
* Display display =
* ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE
* )).getDefaultDisplay(); displayWidth = display.getWidth();
* displayHeight = display.getHeight();
*/
//ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
/*
* iv.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View arg0) { // TO DO Auto-generated
* method stub
*
* BrushView view = new BrushView(getActivity()); //setContentView(new
* BrushView(this)); } });
*/
//return view;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
public class BrushView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public Button btnEraseAll;
public LayoutParams params;
public BrushView(Context paintFragment) {
super(paintFragment);
brush.setAntiAlias(true);
brush.setColor(Color.BLUE);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(15f);
btnEraseAll = new Button(paintFragment);
btnEraseAll.setText("Erase Everything!!");
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
btnEraseAll.setLayoutParams(params);
btnEraseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// reset the path
path.reset();
// invalidate the view
postInvalidate();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
// Force a view to draw.
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
}
}
Thanks In Advance...

Categories