I got my MainActivity class extends as AppCompatActivity but I want to add a new activity as below. I tried to use intent to add it into the MainActivity. However, when I open the app, it crashes when I trigger the function. Here are the codes for two activities.
MainActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.michael.jared.navigationdrawerloginsqlite.database.DatabaseManagerUser;
import com.michael.jared.navigationdrawerloginsqlite.entity.User;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DatabaseManagerUser databaseManagerUser;
private User itemUsuario;
private String ident;
public ViewPagerActivity vpa;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//se agrego codigo del 39 al 68
Bundle b = getIntent().getExtras();
ident = b.getString("IDENT");
databaseManagerUser= new DatabaseManagerUser(getApplicationContext());
itemUsuario = databaseManagerUser.getUsuario(ident); // encuentra al usuario registrado en la bbdd
View header = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
((TextView) header.findViewById(R.id.tv_nombre_usuario_menu)).setText(itemUsuario.getNombre());
((TextView) header.findViewById(R.id.tv_correo_menu)).setText(itemUsuario.getCorreo());
Bitmap bitmapsinfoto = BitmapFactory.decodeResource(getResources(),R.drawable.imagen);
RoundedBitmapDrawable roundedBitmapDrawablesinfoto = RoundedBitmapDrawableFactory.create(getResources(), bitmapsinfoto);
roundedBitmapDrawablesinfoto.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawablesinfoto);
if(itemUsuario.getBytes()!=null){
byte[] foodImage = itemUsuario.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
((ImageView) header.findViewById(R.id.imageView)).setImageBitmap(bitmap);
Bitmap bitmap2 = ((BitmapDrawable)((ImageView) header.findViewById(R.id.imageView)).getDrawable()).getBitmap();
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap2);
roundedBitmapDrawable.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawable);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
} else if (id == R.id.nav_fourth_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FourthFragment())
.commit();
} else if (id == R.id.nav_share) {
startActivity(new Intent(this, ViewPagerActivity.class));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ViewPagerActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.annotation.SuppressLint;
import android.os.Build;
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.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
#SuppressLint("NewApi")
public class ViewPagerActivity extends FragmentActivity implements
ScrollTabHolder, ViewPager.OnPageChangeListener {
public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK_INT).intValue() < 11;
private View mHeader;
private PagerSlidingTabStrip mPagerSlidingTabStrip;
private ViewPager mViewPager;
private PagerAdapter mPagerAdapter;
private int mMinHeaderHeight;
private int mHeaderHeight;
private int mMinHeaderTranslation;
private TextView info;
private int mLastY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
mMinHeaderTranslation = -mMinHeaderHeight;
setContentView(R.layout.activity_main);
mHeader = findViewById(R.id.header);
info = (TextView) findViewById(R.id.info);
mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.setTabHolderScrollingContent(this);
mViewPager.setAdapter(mPagerAdapter);
mPagerSlidingTabStrip.setViewPager(mViewPager);
mPagerSlidingTabStrip.setOnPageChangeListener(this);
mLastY=0;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// nothing
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffsetPixels > 0) {
int currentItem = mViewPager.getCurrentItem();
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder;
if (position < currentItem) {
currentHolder = scrollTabHolders.valueAt(position);
} else {
currentHolder = scrollTabHolders.valueAt(position + 1);
}
if (NEEDS_PROXY) {
// TODO is not good
currentHolder.adjustScroll(mHeader.getHeight() - mLastY);
mHeader.postInvalidate();
} else {
currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
}
}
}
#Override
public void onPageSelected(int position) {
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);
if(NEEDS_PROXY){
//TODO is not good
currentHolder.adjustScroll(mHeader.getHeight()-mLastY);
mHeader.postInvalidate();
}else{
currentHolder.adjustScroll((int) (mHeader.getHeight() +mHeader.getTranslationY()));
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount, int pagePosition) {
if (mViewPager.getCurrentItem() == pagePosition) {
int scrollY = getScrollY(view);
if(NEEDS_PROXY){
//TODO is not good
mLastY=-Math.max(-scrollY, mMinHeaderTranslation);
info.setText(String.valueOf(scrollY));
mHeader.scrollTo(0, mLastY);
mHeader.postInvalidate();
}else{
mHeader.setTranslationY(Math.max(-scrollY, mMinHeaderTranslation));
}
}
}
#Override
public void adjustScroll(int scrollHeight) {
// nothing
}
public int getScrollY(AbsListView view) {
View c = view.getChildAt(0);
if (c == null) {
return 0;
}
int firstVisiblePosition = view.getFirstVisiblePosition();
int top = c.getTop();
int headerHeight = 0;
if (firstVisiblePosition >= 1) {
headerHeight = mHeaderHeight;
}
return -top + firstVisiblePosition * c.getHeight() + headerHeight;
}
public static float clamp(float value, float max, float min) {
return Math.max(Math.min(value, min), max);
}
public class PagerAdapter extends FragmentPagerAdapter {
private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
private final String[] TITLES = { "Page 1", "Page 2", "Page 3", "Page 4"};
private ScrollTabHolder mListener;
public PagerAdapter(FragmentManager fm) {
super(fm);
mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
}
public void setTabHolderScrollingContent(ScrollTabHolder listener) {
mListener = listener;
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
ScrollTabHolderFragment fragment = (ScrollTabHolderFragment) SampleListFragment.newInstance(position);
mScrollTabHolders.put(position, fragment);
if (mListener != null) {
fragment.setScrollTabHolder(mListener);
}
return fragment;
}
public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
return mScrollTabHolders;
}
}
}
Related
I need a side drawer layout, with a navigation view that contains a few buttons, doing different things. The issue I am having is that when I go to add ANYTHING within my "onNavigationItemSelected" listener, it never does anything. Basically, I assign the drawer+nav view, then do the ActionBarDrawerToggle with the proper items, and add the DrawerListener, then sync, then add the NavItemSelectedListener. This doesn't work. (Won't respond to clicks)
Here's the code:
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerlayout);
navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void replaceFragment(Fragment fragment,String title) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in,
R.anim.fade_out,
R.anim.fade_in,
R.anim.slide_out)
.setReorderingAllowed(true)
.replace(R.id.frameLayout, fragment,title)
.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
replaceFragment(new Auto(),"auto");
return false;
}
If this doesn't give a clear answer, here is ALL of the code for this task.
package com.gtappdevelopers.firebasestorageimage;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.gtappdevelopers.firebasestorageimage.databinding.ActivityMainBinding;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
ActivityMainBinding binding;
FloatingActionButton fab;
static String balance = "NA";
static int match = -1;
static int team = -1;
static String autoC = "NA";
static String teleC = "NA";
public static int dimen;
static ArrayList<Integer> grid;
static ArrayList<Integer> teleGrid;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new BeforeMatchFragment(),"before");
fab = findViewById(R.id.fab);
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
//initializing a variable for default display.
Display display = manager.getDefaultDisplay();
//creating a variable for point which is to be displayed in QR Code.
Point point = new Point();
display.getSize(point);
//getting width and height of a point
int width = point.x;
int height = point.y;
//generating dimension from width and height.
dimen = Math.min(width, height);
dimen = dimen * 3 / 4;
fab.setOnClickListener(this);
while (!checkPermission()) {
requestPermission();
}
binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.before:
replaceFragment(new BeforeMatchFragment(),"before");
break;
case R.id.auto:
replaceFragment(new Auto(),"auto");
break;
case R.id.tele:
replaceFragment(new TeleOp(),"tele");
break;
case R.id.end:
replaceFragment(new EndGame(),"end");
break;
case R.id.dock:
replaceFragment(new Docking(),"docking");
break;
}
return true;
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.newTeam:
Intent intent = new Intent(MainActivity.this,MainActivity.class);
startActivity(intent);
break;
case R.id.FileViewer:
Intent intent1= new Intent(MainActivity.this,FileListActivity.class);
startActivity(intent1);
break;
case R.id.NightMode:
SplashActivity.setNight();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fab:
BeforeMatchFragment beforeFrag = (BeforeMatchFragment)getSupportFragmentManager().findFragmentByTag("before");
EndGame endFrag = (EndGame)getSupportFragmentManager().findFragmentByTag("end");
Auto autoFrag = (Auto)getSupportFragmentManager().findFragmentByTag("auto");
TeleOp teleFrag = (TeleOp)getSupportFragmentManager().findFragmentByTag("tele");
Docking dockFrag = (Docking)getSupportFragmentManager().findFragmentByTag("docking");
if (beforeFrag != null && beforeFrag.isVisible()) {
Intent intent = new Intent(MainActivity.this,SplashActivity.class);
startActivity(intent);
}else if (autoFrag != null && autoFrag.isVisible()) {
binding.bottomNavigationView.setSelectedItemId(R.id.before);
replaceFragment(new BeforeMatchFragment(), "before");
}else if (teleFrag != null && teleFrag.isVisible()) {
binding.bottomNavigationView.setSelectedItemId(R.id.auto);
replaceFragment(new Auto(), "auto");
}else if (endFrag != null && endFrag.isVisible()) {
binding.bottomNavigationView.setSelectedItemId(R.id.dock);
replaceFragment(new Docking(), "docking");
}else if (dockFrag != null && dockFrag.isVisible()) {
binding.bottomNavigationView.setSelectedItemId(R.id.tele);
replaceFragment(new TeleOp(), "tele");
}
break;
}
}
private void replaceFragment(Fragment fragment,String title) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
.setCustomAnimations(R.anim.slide_in,
R.anim.fade_out,
R.anim.fade_in,
R.anim.slide_out)
.setReorderingAllowed(true)
.replace(R.id.frameLayout, fragment,title)
.addToBackStack(null);
fragmentTransaction.commit();
}
public boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_GRANTED) {
return true;
}else{
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this,"Storage permission is required, please allow it from settings.",Toast.LENGTH_SHORT).show();
}else{
ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},111);
}
}
public static void setBalance(String balance) {
MainActivity.balance = balance;
}
public static void setMatch(int match) {
MainActivity.match = match;
}
public static void setTeam(int team) {
MainActivity.team = team;
}
public static void setAutoC(String autoC) {
MainActivity.autoC = autoC;
}
public static void setTeleC(String teleC) {
MainActivity.teleC = teleC;
}
public static void setGrid( ArrayList<Integer> grid) {
MainActivity.grid = grid;
}
public static void setTeleGrid( ArrayList<Integer> teleGrid) {
MainActivity.teleGrid = teleGrid;
}
public static int getDimen() {
return dimen;
}
public static int getMatch() {
return match;
}
public static int getTeam() {
return team;
}
public static String getAutoC() {
return autoC;
}
public static String getTeleC() {
return teleC;
}
public static String getBalance() {
return balance;
}
public static ArrayList<Integer> getGrid() {
return grid;
}
public static ArrayList<Integer> getTeleGrid() {
return teleGrid;
}
public static String getAllData(){
return String.valueOf(match) + "\n" + String.valueOf(team) + "\n" + autoC + "\n" + grid.toString() + "\n" + teleC + "\n" + teleGrid.toString() + "\n" + balance;
}
public static void clearData(){
match = -1;
team = -1;
autoC = "NA";
grid = new ArrayList<Integer>();
for (int i = 0; i < 27; i++) {
grid.add(i,0);
}
teleC = "NA";
teleGrid = new ArrayList<Integer>();
for (int i = 0; i < 27; i++) {
teleGrid.add(i,0);
}
balance = "NA";
}
}
I have tried using a switch statement to detect which ID clicked the Item, but none worked. Then I tried making it so that ANY item that clicked the navigationView made the entire screen swap fragments. This did not work. Then, I tried getting a Toast.makeText() to show up when I clicked ANY Item, this did not work. I'm expecting the bug to be somewhere within my NavView set up/on create code.
EDIT: The answer was that within my XML, my NavigationView was before my actual content within the screen. You must put the nav View AFTER the layout, be it relative, constraint, etc. It should be the last thing in the drawer layout, basically. This answer was given to me by Mike M. Thanks Mike!
Here is my code.
I try to add OnItenClickListener to "lastCommand" listView but it is not responde. Any errors at compile.
package pl.globoox.sprawdzsprzedawce;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import pl.globoox.sprawdzsprzedawce.Utils.LastCommentHome;
import pl.globoox.sprawdzsprzedawce.Utils.QueryCheck;
import static pl.globoox.sprawdzsprzedawce.R.id.buttonCheckButton;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView lastComments;
LoginButton loginButton;
CallbackManager callbackManager;
ArrayList<String> comments_userList = new ArrayList();
ArrayList<String> comments_olxUserList = new ArrayList();
ArrayList<String> comments_dateList = new ArrayList();
ArrayList<String> comments_messageList = new ArrayList();
ArrayList<String> comments_statusList = new ArrayList();
ImageView imageViewFBUser;
TextView textViewFBName;
TextView textViewFBEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
initializeControls();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginWithFb();
// MENU DRAWER
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
textViewFBName = headerView.findViewById(R.id.textViewFBName);
textViewFBEmail = headerView.findViewById(R.id.textViewFBEmail);
imageViewFBUser = headerView.findViewById(R.id.imageViewFBUser);
imageViewFBUser.setVisibility(View.INVISIBLE);
textViewFBName.setText("");
textViewFBEmail.setText("");
// MAIN CONTENT APP
final SearchView editTextOfferLink = (SearchView) findViewById(R.id.editTextOfferLink);
final Button buttonCheck = (Button) findViewById(buttonCheckButton);
lastComments = (ListView) findViewById(R.id.listViewLastComments);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String offerLink = editTextOfferLink.getQuery().toString();
boolean error = false;
// CHECK FORM EMPTY
if (offerLink.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.formEmpty).setNegativeButton(R.string.tryAgain, null).create().show();
error = true;
return;
}
if (error == false) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
String userID = jsonResponse.getString("userID");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.cantConnectToDatabase).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER NOT FOUND
else if (errorCode == 2) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), AddNewUserActivity.class);
if (isBank == true) {
i.putExtra("isBank", "true");
} else {
i.putExtra("isBank", "false");
}
String userName = jsonResponse.getString("userName");
String registerDate = jsonResponse.getString("registerDate");
i.putExtra("userID", userID);
i.putExtra("userName", userName);
i.putExtra("registerDate", registerDate);
finish();
startActivity(i);
}
// EMPTY OFFER VARIABLE
else if (errorCode == 3) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.omptyOfferVariable).setNegativeButton(R.string.tryAgain, null).create().show();
}
// BAD LINK
else if (errorCode == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.badOfferLink).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER FOUND!
else if (errorCode == 5) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), UserAreaActivity.class);
i.putExtra("userID", userID);
i.putExtra("isBank", isBank.toString());
finish();
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
QueryCheck offerQueryRequest = new QueryCheck(offerLink, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(offerQueryRequest);
}
}
});
// LAST COMMENTS SHOW
Response.Listener<String> responseListenerLastComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
int count = jsonResponse.getInt("count");
Log.d("Tag", String.valueOf(errorCode));
JSONArray commentsArray = jsonResponse.getJSONArray("comments");
Log.d("TAG", String.valueOf(commentsArray));
for (int i = 0; i < count; i++) {
JSONObject jsonObject = commentsArray.getJSONObject(i);
comments_userList.add(jsonObject.getString("user"));
comments_olxUserList.add(jsonObject.getString("olxUser"));
comments_dateList.add(jsonObject.getString("date"));
comments_messageList.add(jsonObject.getString("message"));
comments_statusList.add(jsonObject.getString("status"));
}
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
lastComments.setAdapter(customAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LastCommentHome lastCommentHome = new LastCommentHome("3", responseListenerLastComments);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(lastCommentHome);
}
private void loginWithFb() {
// LOGIN MANAGER FACEBOOK
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String name = me.optString("name");
String picture = me.optString("picture");
imageViewFBUser.setVisibility(View.VISIBLE);
imageViewFBUser.setImageURI(Uri.parse(picture));
textViewFBName.setText(name);
textViewFBEmail.setText(email);
}
}
}).executeAsync();
}
#Override
public void onCancel() {
textViewFBName.setText("Login canceled!");
}
#Override
public void onError(FacebookException error) {
textViewFBName.setText("Login error: " + error.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
// FACEBOOK INITALZIZE LOGIN
private void initializeControls() {
callbackManager = CallbackManager.Factory.create();
loginButton = findViewById(R.id.login_button);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
// Handle the camera action
} else if (id == R.id.nav_best) {
} else if (id == R.id.nav_worst) {
} else if (id == R.id.nav_comments) {
} else if (id == R.id.nav_policy) {
} else if (id == R.id.nav_rules) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contact) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
lastComments.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("asdasdxxxxx", String.valueOf(position));
}});
return convertView;
}
}
}
You can create your own interface :
private interface OnListItemClickListener
{
void onListItemClicked(View view, int position);
}
Then use it in your adapter class this way:
class CustomAdapter extends BaseAdapter {
//create an instance
private OnListItemClickListener onListItemClickListener;
//define the object setter
void setOnListItemClickListener(OnListItemClickListener listener)
{
this.onListItemClickListener=listener;}
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
//Then here trigger
convertView.setOnClickListener(new View.OnClickListener()
{
#override
void onClick(View v)
{
onListItemClickListener.onListItemClicked(v,position);
//you may be asked to set position as final
}
});
return convertView;
}
}
Then in your onCreate method where you attached the adapter, set the listener to your adapter:
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
customAdapter.setOnListItemClickListener(new OnListItemClickListener()
{
#override
void onListItemClicked(View view,int position)
{
//then here place your desired action
}
});
lastComments.setAdapter(customAdapter);
I hope this may be helpful. You can still ask for clarifications in comment
I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#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 OnFragmentNavListener {
void onFragmentNav(int position);
}
}
Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved
i'm trying to make a navigation to one of my fragment but I can't seem to invoke that fragment here's my code
MainActivity.java
package ics115_4ite_lim.bookings;
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import ics115_4ite_lim.bookings.Fragments.ScheduleFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the fragment I want to go to
ScheduleFragment.java
package ics115_4ite_lim.bookings.Fragments;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.daimajia.swipe.util.Attributes;
import java.util.ArrayList;
import ics115_4ite_lim.bookings.DividerItemDecoration;
import ics115_4ite_lim.bookings.R;
import ics115_4ite_lim.bookings.Student;
/**
* Created by Mark Terrance on 12/7/2017.
*/
public class ScheduleFragment extends Fragment {
private ArrayList<Student> mDataSet;
private Toolbar toolbar;
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment_packages
final View view = inflater.inflate(R.layout.schedule_fragment, container, false);
initScheduleView(view);
return view;
}
private void initScheduleView(View view){
mRecyclerView = view.findViewById(R.id.recycleView);
// Layout Managers:
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// Item Decorator:
//mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mDataSet = new ArrayList<Student>();
loadData();
if (mDataSet.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(getActivity(), mDataSet);
// Setting Mode to Single to reveal bottom View for one item in List
// Setting Mode to Mutliple to reveal bottom Views for multile items in List
((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
mRecyclerView.setAdapter(mAdapter);
/* Scroll Listeners */
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.e("RecyclerView", "onScrollStateChanged");
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
}
// load initial data
public void loadData() {
for (int i = 0; i <= 20; i++) {
mDataSet.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
private class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {
private Context mContext;
private ArrayList<Student> studentList;
public SwipeRecyclerViewAdapter(Context context, ArrayList<Student> objects) {
this.mContext = context;
this.studentList = objects;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_row_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
final Student item = studentList.get(position);
viewHolder.tvName.setText((item.getName()) + " - Row Position " + position);
viewHolder.tvEmailId.setText(item.getEmailId());
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
// Drag From Left
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
/*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
//Start your activity
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
}
});*/
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Edit " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
studentList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, studentList.size());
mItemManger.closeAllItems();
Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
// mItemManger is member in RecyclerSwipeAdapter Class
mItemManger.bindView(viewHolder.itemView, position);
}
#Override
public int getItemCount() {
return studentList.size();
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
// ViewHolder Class
public class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView tvName;
TextView tvEmailId;
TextView tvDelete;
TextView tvEdit;
TextView tvShare;
ImageButton btnLocation;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
tvShare = (TextView) itemView.findViewById(R.id.tvShare);
btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
}
}
}
}
I have tried debugging it and I ended up on a null fragment
I don't know what's wrong because I just followed a tutorial
Help pls ? thanks :D
edit:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="ics115_4ite_lim.bookings.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
You need to actually do something with the Fragment you created.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_id, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Make sure your fragment is not null, all your if branches should
initialize it to something
R.id.container_id should be an id of a ViewGroup in your layout that is empty and this is where the fragment will be placed.
My navigation drawer only show the first fragment class and 1 other class.I have 8 fragment class for menu in my drawer. When I click the other fragment class, it will be blank.
Here is the NavigationDrawerFragment.java :
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
public RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem(getString(R.string.Home), getResources().getDrawable(R.drawable.ico_home)));
items.add(new NavigationItem(getString(R.string.Map), getResources().getDrawable(R.drawable.ico_map)));
items.add(new NavigationItem(getString(R.string.Departments), getResources().getDrawable(R.drawable.ico_dpt)));
items.add(new NavigationItem(getString(R.string.Units), getResources().getDrawable(R.drawable.ico_unit)));
items.add(new NavigationItem(getString(R.string.Gallery), getResources().getDrawable(R.drawable.ico_gallery)));
items.add(new NavigationItem(getString(R.string.AboutPSIS), getResources().getDrawable(R.drawable.ico_about)));
items.add(new NavigationItem(getString(R.string.Help), getResources().getDrawable(R.drawable.ico_help)));
items.add(new NavigationItem(getString(R.string.Credits), getResources().getDrawable(R.drawable.ico_credit)));
return items;
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
* #param toolbar The Toolbar of the activity.
*/
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = (View) getActivity().findViewById(fragmentId).getParent();
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
/*
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
*/
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
this class handle the drawer click :
package com.example.tropo;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch (position) {
case 0: //Home
fragment = getFragmentManager().findFragmentByTag(D_Home.TAG);
if (fragment == null) {
fragment = new D_Home();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Home.TAG).commit();
break;
case 1: //Map
fragment = getFragmentManager().findFragmentByTag(D_Map.TAG);
if (fragment == null) {
fragment = new D_Map();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Map.TAG).commit();
break;
case 2: //Departments
fragment = getFragmentManager().findFragmentByTag(D_Departments.TAG);
if (fragment == null) {
fragment = new D_Departments();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Departments.TAG).commit();
break;
case 3: //Units
fragment = getFragmentManager().findFragmentByTag(D_Units.TAG);
if (fragment == null) {
fragment = new D_Units();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Units.TAG).commit();
break;
case 4: //Gallery
fragment = getFragmentManager().findFragmentByTag(D_Gallery.TAG);
if (fragment == null) {
fragment = new D_Gallery();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Gallery.TAG).commit();
break;
case 5: //About PSIS
fragment = getFragmentManager().findFragmentByTag(D_About.TAG);
if (fragment == null) {
fragment = new D_About();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_About.TAG).commit();
break;
case 6: //Help
fragment = getFragmentManager().findFragmentByTag(D_Help.TAG);
if (fragment == null) {
fragment = new D_Help();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Help.TAG).commit();
break;
case 7: //Credit
fragment = getFragmentManager().findFragmentByTag(D_Credit.TAG);
if (fragment == null) {
fragment = new D_Credit();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, D_Credit.TAG).commit();
break;
}
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#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);
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();
return super.onOptionsItemSelected(item);
}
public void onActivityCreated(Bundle savedInstanceState) {
}
}