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
Related
I have a Fragment pager adapter with five fragments and inside the third fragment I want to call an other activity which sends a selected picture to the container. It works fine but, every time the picture is selected from the other activity and the pager adapter starts from the first fragment in the fragment-activity instead of third fragment-activity. Do I have to force the pager adapter from the other activity or should I change something in the fragment-activity?
Code:
Fragment-activity:
package com.example.android.womb_the_game;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
public class Circulation extends FragmentActivity {
ViewPager vp;
public static FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_circulation);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
vp = findViewById(R.id.view_pager);
adapterViewPager=new Adapter_Circulation(getSupportFragmentManager(), this);
vp.setAdapter(adapterViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(vp);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
FragmentPagerAdapter:
package com.example.android.womb_the_game;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import android.content.Context;
public class Adapter_Circulation extends FragmentPagerAdapter {
private static int NUM_ITEMS = 5;
Context context;
public Adapter_Circulation(FragmentManager fm, Context c) {
super(fm);
this.context = c;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return Frg0.newInstance ();
case 1:
return Frg1.newInstance();
case 2:
return Frg2.newInstance();
case 3:
return Frg3.newInstance();
case 4:
return Frg4.newInstance();
}
return null; //does not happen
}
#Override
public int getCount() {
return NUM_ITEMS; //three fragments
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RULES";
case 1:
return "EVENTS";
case 2:
return "PLAN";
case 3:
return "SHOOT";
case 4:
return "JUMP";
}
return null;
}
}
Fragment3:
package com.example.android.womb_the_game;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class Frg3 extends Fragment{
private ImageButton shoot;
private ImageButton snipe;
private ImageButton aim;
public static Frg3 newInstance() {
Bundle args = new Bundle();
Frg3 fragment = new Frg3();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_frg3, container, false);
shoot = (ImageButton) rootView.findViewById(R.id.shoot);
snipe = (ImageButton) rootView.findViewById(R.id.snipe);
aim = (ImageButton) rootView.findViewById(R.id.aim);
final View.OnClickListener mListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.shoot:
FragmentManager FM0 = getFragmentManager();
FragmentTransaction FT0 = FM0.beginTransaction();
frg_shoot F10 = new frg_shoot();
FT0.add(R.id.fragment_container1, F10);
FT0.replace(R.id.fragment_container1, F10);
FT0.commit();
break;
case R.id.snipe:
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
frg_snipe F1 = new frg_snipe();
FT.add(R.id.fragment_container1, F1);
FT.replace(R.id.fragment_container1, F1);
FT.commit();
break;
case R.id.aim:
FragmentManager FM1 = getFragmentManager();
FragmentTransaction FT1 = FM1.beginTransaction();
frg_aim F11 = new frg_aim();
FT1.add(R.id.fragment_container1, F11);
FT1.replace(R.id.fragment_container1, F11);
FT1.commit();
break;
}
}
};
rootView.findViewById(R.id.shoot).setOnClickListener(mListener);
rootView.findViewById(R.id.snipe).setOnClickListener(mListener);
rootView.findViewById(R.id.aim).setOnClickListener(mListener);
return rootView;
}
}
Other Activity:
package com.example.android.womb_the_game;
import androidx.fragment.app.FragmentActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
public class choose_dice_column extends FragmentActivity {
private ImageButton b1;
private ImageView im1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_choose_dice_column);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
b1 = (ImageButton) findViewById(R.id.b1);
im1 = findViewById(R.id.im1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(choose_dice_column.this, Circulation.class);
i.putExtra("resid1",R.drawable.n1);
startActivity(i);
}
});
}
}
The problem is, whenever you get back to your activity, you are creating a new adapter. So add the following to your Circulation-Activity to keep the state of the adapter:
if(adapterViewPager == null)
{
adapterViewPager = new Adapter_Circulation(getSupportFragmentManager(), this);
}
I have implemented navigation drawer on my mobile application and whenever i open the drawer and click on the drawer, the drawer closes itself. It used to work perfectly until I implemented another function and I am puzzled about how I should fix this.
Here's my main activity code. I am unable to navigate using the navigation drawer now.
package com.example.admin.calendlist;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
ListView lstTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
dbHelper = new DatabaseHelper(this);
lstTask = (ListView)findViewById(R.id.lstTask);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView nvDrawer = (NavigationView)findViewById(R.id.nav_view);
setupDrawerContent(nvDrawer);
loadTaskList();
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.row,R.id.task_title,taskList);
lstTask.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
{
switch (item.getItemId()) {
case R.id.action_add_task:
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
dbHelper.insertNewTask(task);
loadTaskList();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
switch (item.getItemId()) {
case R.id.td:
Intent newIntent = new Intent(this,MainActivity.class);
return true;
}
switch (item.getItemId()) {
case R.id.tt:
Intent newIntent = new Intent(this,Timetable.class);
return true;
}
switch (item.getItemId()) {
case R.id.ep:
Intent newIntent = new Intent(this,EventPage.class);
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void selectItemDrawer(MenuItem item) {
int id = item.getItemId();
if (id ==R.id.ep) {
Intent newItent = new Intent (this, EventPage.class);
startActivity(newItent);
}
else if (id == R.id.td) {
Intent newIntent = new Intent (this,MainActivity.class);
startActivity(newIntent);
}
else if (id == R.id.tt) {
Intent newIntent = new Intent (this,Timetable.class);
startActivity(newIntent);
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
private void setupDrawerContent (NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener (new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.listmenu,menu);
Drawable icon =menu.getItem(0).getIcon();
icon.mutate();
icon.setColorFilter(getResources().getColor(android.R.color.black), PorterDuff.Mode.SRC_IN);
return super.onCreateOptionsMenu(menu);
}
public void deleteTask(View view){
View parent = (View)view.getParent();
TextView taskTextView = (TextView)findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
dbHelper.deleteTask(task);
loadTaskList();
}
}
If you don't want navigation to close with each click, write like this :
NavigationView navigationView = findViewById(R.id.navigationView);
navigationView.bringToFront();
you can use it after switch
switch(id){
}
//Set menuItem checked and title
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
return false;
its obvious in Default drawerlayout on your click it has to be close,if you wana get command on your drawerlayot , hen you have to use custom drawerlayout, or you can add the library, don't forget to import the library manually not in your gradle, then you can edit the library, and chose the functions .
try this Library
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);
}
}
Im desperate. Im trying to add an onClickListener in a Fragment class.
The idea is that I have a ViewPager with images. All I want is to click on an image itself and have it display a toast message. I know you cant register an OnClickListener to the ViewPager itself, so I tried adding it in the Fragment class that handles the ImageView.
What happens now is, the onClick method works, if I click on one of the images, it displays a message, but it keeps displaying the DEFAULT switch case I use. I just cant for the life of me understand why......! :(
Here's the code maybe you can see a solution?
Thanks.
MainActivity:
package com.example.viewpagerexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity{
private static final int NUM_PAGES = 5;
private MyAdapter mAdapter;
private ViewPager mPager;
private Button leftBTN;
private Button rightBTN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
leftBTN = (Button)findViewById(R.id.leftBTN);
leftBTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(mPager.getCurrentItem()-1, true);
}
});
rightBTN = (Button)findViewById(R.id.rightBTN);
rightBTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(mPager.getCurrentItem()+1, true);
}
});
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public Fragment getItem(int position) {
ImageFragment myFragment = new ImageFragment();
Bundle data = new Bundle();
data.putInt("current_page", position);
myFragment.setArguments(data);
return myFragment;
}
}
}
And here is the Fragment class with the OnClickListener implementation:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageFragment extends Fragment implements OnClickListener{
private int position;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
position = data.getInt("current_page", 0);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_details, container, false);
imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setOnClickListener(this);
switch (position) {
case 0:
imageView.setImageResource(R.drawable.splash);
return view;
case 1:
imageView.setImageResource(R.drawable.girrafe);
return view;
case 2:
imageView.setImageResource(R.drawable.lion);
return view;
case 3:
imageView.setImageResource(R.drawable.monkey);
return view;
case 4:
imageView.setImageResource(R.drawable.chicken);
return view;
default:
return null;
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.drawable.splash:
Log.d("DEBUG", "image 0 pressed");
Toast.makeText(getActivity(), "Pic 1", Toast.LENGTH_SHORT).show();
return;
case R.drawable.girrafe:
Log.d("DEBUG", "image 1 pressed");
Toast.makeText(getActivity(), "Pic 2", Toast.LENGTH_SHORT).show();
return;
case R.drawable.lion:
Log.d("DEBUG", "image 2 pressed");
Toast.makeText(getActivity(), "Pic 3", Toast.LENGTH_SHORT).show();
return;
case R.drawable.monkey:
Log.d("DEBUG", "image 3 pressed");
Toast.makeText(getActivity(), "Pic 4", Toast.LENGTH_SHORT).show();
return;
case R.drawable.chicken:
Log.d("DEBUG", "image 4 pressed");
Toast.makeText(getActivity(), "Pic 5", Toast.LENGTH_SHORT).show();
return;
default:
Log.d("DEBUG", "v.getId(): " + v.getId());
Log.d("DEBUG", "default pressed");
Toast.makeText(getActivity(), "DEFAULT pressed!", Toast.LENGTH_SHORT).show();
return;
}
}
}
I think that in your onclick method, v.getId()(id of clicked view) returns always R.id.imageView1, that is why you are always getting the default switch case in onClick.
You set onClickListener to your imageView, but you forgot to change the id of the imageview so the id is still R.id.imageView1 and your listener cannot handle it properly.
Try to edit switch statement of your onCreateView method like this:
switch (position) {
case 0:
imageView.setImageResource(R.drawable.splash);
imageView.setId(R.drawable.splash);
return view;
case 1:
imageView.setImageResource(R.drawable.girrafe);
imageView.setId(R.drawable.girrafe);
return view;
case 2:
imageView.setImageResource(R.drawable.lion);
imageView.setId(R.drawable.lion);
return view;
case 3:
imageView.setImageResource(R.drawable.monkey);
imageView.setId(R.drawable.monkey);
return view;
case 4:
imageView.setImageResource(R.drawable.chicken);
imageView.setId(R.drawable.chicken);
return view;
default:
return null;
}