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);
}
Related
I have a 3 fragment, and in the last fragment I have some buttons to redirect user to open a link,
enter image description here
but it doesn't work. here is my fragment activity
package com.vyzyz.covidupdate.fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.vyzyz.covidupdate.R;
/**
* A simple {#link Fragment} subclass.
*/
public class InfoFragment extends Fragment implements View.OnClickListener {
public InfoFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_info, container, false);
Button btnHospital = (Button)v.findViewById(R.id.BtnInfoHospital);
Button btnSymptom = (Button)v.findViewById(R.id.BtnInfoSymptom);
Button btnPrevention = (Button)v.findViewById(R.id.BtnInfoPrevention);
Button btnAdviceWho = (Button)v.findViewById(R.id.BtnInfoAdviceWho);
btnHospital.setOnClickListener(this);
btnSymptom.setOnClickListener(this);
btnPrevention.setOnClickListener(this);
btnAdviceWho.setOnClickListener(this);
return v;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnInfoHospital:
String hospitalUrl = "https://news.detik.com/berita/d-4942353/daftar-rumah-sakit-rujukan-covid-19-seluruh-indonesia?single=1";
Uri hospitalUri = Uri.parse(hospitalUrl);
Intent intentInfoHospital = new Intent(Intent.ACTION_VIEW, hospitalUri);
// Toast.makeText(this, getResources().getString(R.string.redirect), Toast.LENGTH_SHORT).show();
startActivity(intentInfoHospital);
break;
case R.id.btnInfoSymptom:
String symptomUrl = "https://www.cnnindonesia.com/gaya-hidup/20200128205625-258-469589/infografis-bedanya-demam-selesma-dan-virus-corona-wuhan";
Uri symptomUri = Uri.parse(symptomUrl);
Intent intentInfoSymptom = new Intent(Intent.ACTION_VIEW, symptomUri);
//Toast.makeText(this, getResources().getString(R.string.redirect), Toast.LENGTH_SHORT).show();
startActivity(intentInfoSymptom);
break;
case R.id.btnInfoPrevention:
String urlPrevention = "https://www.kompas.com/sains/read/2020/03/15/190200123/panduan-mencegah-virus-corona-pesan-who-untuk-kita-semua?page=all#page4";
Uri preventionUri = Uri.parse(urlPrevention);
Intent intentPrevention = new Intent(Intent.ACTION_VIEW, preventionUri);
//Toast.makeText(this, getResources().getString(R.string.redirect), Toast.LENGTH_SHORT).show();
startActivity(intentPrevention);
break;
case R.id.btnInfoAdviceWho:
String urlWho = "https://www.youtube.com/watch?v=bPITHEiFWLc&feature=emb_title";
Uri whoUri = Uri.parse(urlWho);
Intent intentWho = new Intent(Intent.ACTION_VIEW, whoUri);
// Toast.makeText(this, getResources().getString(R.string.redirect), Toast.LENGTH_SHORT).show();
startActivity(intentWho);
break;
}
}
}
and here is my main, activity
package com.vyzyz.covidupdate.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.vyzyz.covidupdate.R;
import com.vyzyz.covidupdate.fragment.IdnFragment;
import com.vyzyz.covidupdate.fragment.InfoFragment;
import com.vyzyz.covidupdate.fragment.SummaryFragment;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Menampilkan Fragment Summary Ketika App Dibuka
SummaryFragment summaryFragment = new SummaryFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.main_frame,summaryFragment)
.commit();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNav);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
//Menu Navigasi Bawah
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
//Ke Fragment Summary
case R.id.summaryMenu:
SummaryFragment summaryFragment = new SummaryFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_frame,summaryFragment)
.commit();
return true;
//Ke Fragment Idn
case R.id.summaryIdnMenu:
IdnFragment idnFragment = new IdnFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_frame,idnFragment)
.commit();
return true;
//ke Fragment News
case R.id.infoMenu:
InfoFragment infoFragment = new InfoFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_frame,infoFragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menampilkan menu utama
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Memilih Masing-Masing Menu pada main menu
switch (item.getItemId()) {
//Ke activity About
case R.id.aboutMenu:
Intent intentAbout = new Intent(this, AboutActivity.class);
startActivity(intentAbout);
break;
}
return super.onOptionsItemSelected(item);
}
}
i've tried to move that fragment to basic activity and the button is work, but, when turn back to fragment, the button doesn't work anymore. I've searching same problem in this site, but it cannot solve my problem.
Anyone can please help me?
you can try this it works for me. Override the onActivityCreated() method and do this.
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button btnHospital = getActivity().findViewById(R.id.BtnInfoHospital);
/// All buttons
btnHospital.setOnClickListener(this);
// All buttons
}
I hope it helps you regards
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 ;)
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);
}
}
I am making some android apps with viewpager in fragment. It shows tabs correct, but I can't see any content in my code. I trying to find and search in stackoverflow and google but I don't know why this code is not working. The code looks strange and i am very sorry about that. I am a first quesiton on here. Thx to help me :-)
This is MainActivity.java
package com.yeungnam.food;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
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.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/* mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START); */
dataList.add(new DrawerItem(true));
dataList.add(new DrawerItem("Message", R.drawable.ic_action_camera));
dataList.add(new DrawerItem("Likes", R.drawable.ic_action_cloud));
dataList.add(new DrawerItem("Games", R.drawable.ic_action_email));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(1);
}
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 1:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 2:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
case 3:
fragment = new FragmentFood();
/* args.putString(FragmentFood.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentFood.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID()); */
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(dataList.get(position).isFirst == false)
SelectItem(position);
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} */
}
This is FragmentFood.java
package com.yeungnam.food;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentFood extends Fragment {
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private FoodAdapter adapter;
public FragmentFood() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_food, container,
false);
tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
pager = (ViewPager) view.findViewById(R.id.pager);
adapter = new FoodAdapter(getActivity());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
return view;
}
public class FoodAdapter extends PagerAdapter {
private final String[] TITLES = { "breafkast", "lunch", "dinner" };
private LayoutInflater mInflater;
public FoodAdapter(Context c) {
super(); mInflater = LayoutInflater.from(c);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Object instantiateItem(ViewGroup pager, int position) {
// looks a little bit messy here
TextView v = new TextView(getActivity());
v.setBackgroundResource(R.color.background_window);
v.setText("PAGE " + (position + 1));
final int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
.getDisplayMetrics());
v.setPadding(padding, padding, padding, padding);
v.setGravity(Gravity.CENTER);
pager.addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object view) {
container.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
}
I also encountered a similar problem,but i use FragmentAdapter. you can refer to the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_first_main, container, false);
textViewMesuemInfo = (TextView) view.findViewById(R.id.textViewMesuemInfo);
textViewOpenInfo = (TextView) view.findViewById(R.id.textViewOpenInfo);
fragmentAdapter = new IntroPagerAdapter(**getChildFragmentManager()**);
sliViewPager = (ViewPager) view.findViewById(R.id.viewPagerMain);
sliViewPager.setOnPageChangeListener(pagerChangeListener);
sliViewPager.setAdapter(fragmentAdapter);
sliViewPager.setCurrentItem(0);
return view;
}
private class IntroPagerAdapter extends FragmentPagerAdapter {
public IntroPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
Log.i("position=",position+"");
switch (position) {
case 0:
return new IntroFragment().setLayout(R.layout.fragment_colckbuild);
case 1:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
case 2:
return new IntroFragment().setLayout(R.layout.fragment_measureinfo);
case 3:
return new IntroFragment().setLayout(R.layout.fragment_playclock);
default:
return null;
}
}
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...