Navigation drawer is under other widgets - java

I'm trying to add fragment with Navigation drawer to the main activity, where are two buttons. However, when Navigation drawer is opened, buttons are above it. Moreover, Navigation drawer is not clickable, but buttons are.
Screenshot of opened Navigation drawer
Here is my code.
XML File implementing Navigation Drawer - MainActivity.xml
<?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"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".MainActivity">
<Button
android:id="#+id/mainTestsButton"
android:layout_width="112dp"
android:layout_height="105dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="334dp"
android:layout_marginEnd="167dp"
android:onClick="goTest"
android:text="Button2"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/mainLearningButton"
android:layout_width="114dp"
android:layout_height="102dp"
android:layout_alignParentEnd="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="108dp"
android:layout_marginEnd="175dp"
android:layout_marginBottom="118dp"
android:onClick="goLearn"
android:text="Button1"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="#+id/fragmentList"
android:name="com.chemistryApps.NavigationDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_navigation_drawer" />
</RelativeLayout>
Navigation Drawer XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
tools:context=".NavigationDrawer">
<android.support.constraint.ConstraintLayout
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</android.support.constraint.ConstraintLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_layout" />
</android.support.v4.widget.DrawerLayout>
Navigation Drawer Fragment Java class
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
public class NavigationDrawer extends Fragment {
private DrawerLayout mDrawerLayout;
NavigationView navigationView;
private OnFragmentInteractionListener mListener;
public NavigationDrawer() {
// Required empty public constructor
}
public static NavigationDrawer newInstance(String param1, String param2) {
NavigationDrawer fragment = new NavigationDrawer();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("buttonClicked", "onCreateView");
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerLayout = view.findViewById(R.id.drawer_layout);
navigationView = view.findViewById(R.id.nav_view);
mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View view, float v) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerOpened(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
navigationView.bringToFront();
mDrawerLayout.requestLayout();
}
#Override
public void onDrawerClosed(#NonNull View view) {
Log.i("buttonClicked", "onDrawerOpened");
}
#Override
public void onDrawerStateChanged(int i) {
Log.i("buttonClicked", "onDrawerOpened");
}
});
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
// set item as selected to persist highlight
Log.i("buttonClicked", "onNavigationItemSelected()" + menuItem.toString());
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
switch (menuItem.getItemId()){
case R.id.learning:
Intent intent = new Intent(getActivity(), LearningActivity.class);
startActivity(intent);
return true;
case R.id.test:
Intent intent2 = new Intent(getActivity(), TestActivity.class);
startActivity(intent2);
return true;
case R.id.settings:
return true;
case R.id.help:
return true;
default:
return false;
}
}
});
return inflater.inflate(R.layout.fragment_navigation_drawer, container,
false);
}
#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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Thank you in advance for an answer.
EDIT:
I am attaching the main activity code
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity implements
NavigationDrawer.OnFragmentInteractionListener {
public void goLearn (View view){
Log.i("buttonClicked", "goLearn");
final Intent intent = new Intent(this, LearningActivity.class);
startActivity(intent);
}
public void goTest (View view){
Log.i("buttonClicked", "goTest");
final Intent intent = new Intent(this, TestActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onFragmentInteraction(Uri uri) {
return;
}
}

Related

ProgressBar does not appear in WebView located in Fragment ,how to show ProgressBar in WebView android?

Whenever, I enter the fragment, I am shown a blank space for a few seconds, then the webpage in the WebView shows up. It seems that the ProgressBar does not show.
Here's my XML file for the Fragment the WebView and ProgressBar is in
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentThree">
<ProgressBar
android:id="#+id/progressbar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"/>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</RelativeLayout>
Here is the Java file for the Fragment Java implementation:
package com.example.task1;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class FragmentThree extends Fragment {
private WebView webView;
private String URL;
private ProgressBar progressBar;
private OnFragmentInteractionListener mListener;
public FragmentThree(String url) {
// Required empty public constructor
this.URL = url;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_three, container, false);
initMain(view);
return view;
}
private void initMain(View view) {
webView = view.findViewById(R.id.webview);
progressBar = view.findViewById(R.id.progressbar);
progressBar.setMax(100);
webView.loadUrl(URL);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setProgress(newProgress);
}
});
}
// 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;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The code is mostly located under the initMain() function for clarification.
Any advice is greatly appreciated, thank you for reading!
Just declare ProgressBar below Webview like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentThree">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
<ProgressBar
android:id="#+id/progressbar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"/>
</RelativeLayout>

How to add an onClickListener that would open a new activity to a Fragment activity

I'm fairly new to android studio so I will try to explain as best as I can.
I've made a menu using fragments, so my activity_home is a fragmented activity. Inside the fragmented activity I've created a button that, upon clicking, should open a new activity.
The problem is that I don't know how to implement the onClickListener inside the fragmented activity.
Every tutorial I went trough does it from the beginning.
This is my main activity:
package com.example.relja.diplomskirad;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new home(), "Home");
adapter.addFragment(new profil(), "Profil");
adapter.addFragment(new mapa(), "Mapa");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
This is my main xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
This is home.java where i want to put the onclick listener:
package com.example.relja.diplomskirad;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class home extends Fragment {
public home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_home, container, false);
}
}
And this is home xml where the button is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".home">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:orientation="vertical">
<LinearLayout
android:id="#+id/glavnaStranica1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/logoSlika"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/logo2"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:id="#+id/glavnaStranica2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginStart="30dp">
<EditText
android:id="#+id/search"
android:layout_width="250dp"
android:layout_height="38dp"
android:hint="#string/search"
android:background="#drawable/ivica"
android:drawableLeft="#drawable/search"
android:drawablePadding="10dp"
android:inputType="text"
/>
<Button
android:id="#+id/dugme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/dugme"
/>
</LinearLayout>
<Button
android:id="#+id/dugmeLogin"
android:layout_width="70dp"
android:layout_height="40dp"
android:text="#string/dugmeLogin"
android:layout_gravity="end"
android:layout_marginRight="10dp"
android:onClick="loginLogin"
style="?android:attr/borderlessButtonStyle"/>
</LinearLayout>
</RelativeLayout>
You can try this.. this will help
public class home extends Fragment {
private Button btn_dumge_login;
public home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn_dumge_login = view.findViewById(R.id.dumgeLogin)
btn_dumge_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), TestActivity.class) ;
getActivity().startActivity(intent);
}
});
}
}
View view = inflater.inflate(R.layout.your_layout_file, container, false);
view.findViewById(R.id.button_id).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
getContext().startActivity(new Intent(getContext(), YourNewActivity.class));
});
return view;
you can use this code in your fragment 'home' in onCreateView() method
You should select first the view you want to be navigated from, for example, the Button with id dugmeLogin
then your code should be something like that
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_home, container, false);
Button loginButton = view.findViewById(R.id.dugmeLogin);
loginButton.setOnClickListener(v -> {
// You code goes here
});
return view;
}
this is in your home.java

Why item on menu drawer can't click ? Android Navigation

I have a really interesting problem with my Navigator menu. I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image. I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
image - this trouble
image - can't click
this my code :
menu_bar.java
package com.database.m.lyburan;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.database.m.lyburan.adapter.EventAdapter;
import com.database.m.lyburan.app.AppController;
import com.database.m.lyburan.data.EventData;
import com.database.m.lyburan.util.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.database.m.lyburan.Buddies.TAG_MESSAGE;
import static com.database.m.lyburan.Login.TAG_USERNAME;
import static com.database.m.lyburan.R.id.parent;
public class menu_bar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
FragmentManager fragmentManager;
Fragment fragment = null;
ListView list;
SharedPreferences sharedpreferences;
SwipeRefreshLayout swipe;
List<EventData> eventList = new ArrayList<EventData>();
private static final String TAG = menu_bar.class.getSimpleName();
private static String url_list = Server.URL + "event.php?offset=";
private int offSet = 0;
int no;
EventAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
private Boolean isFabOpen = false;
private FloatingActionButton fab, fab1, fab2;
private CardView card1, card2;
private Animation fab_open, fab_close, rotate_forward, rotate_backward, card_open, card_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
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);
if (savedInstanceState == null) {
fragment = new Root();
callFragment(fragment);
}
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list_event);
eventList.clear();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(menu_bar.this, Buddies.class);
intent.putExtra(TAG_ID, eventList.get(position).getId());
startActivity(intent);
}
});
adapter = new EventAdapter(menu_bar.this, eventList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callEvent(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
Button meet_buddies = (Button) findViewById(R.id.meet_buddies);
meet_buddies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,Buddies.class);
startActivity(intent);
}
});
Button upcoming = (Button) findViewById(R.id.upcoming);
upcoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,asd.class);
startActivity(intent);
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
card1 = (CardView) findViewById(R.id.card1);
card2 = (CardView) findViewById(R.id.card2);
/*kenalkan animasi*/
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
card_open=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_open);
card_close=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_close);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animateFAB();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(menu_bar.this,Addhome.class);
startActivity(intent);
}
});
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menu_bar.this, "New Call", Toast.LENGTH_SHORT).show();
}
});
}
#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.menu_bar, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_payment) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_help) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.btn_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_containers, fragment)
.commit();
}
public void animateFAB() {
/*jika fab dalam keadaan false*/
if (isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
card1.startAnimation(card_close);
card2.startAnimation(card_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
} else {
/*jika dalam keadaan true*/
fab.startAnimation(rotate_forward);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
card1.startAnimation(card_open);
card2.startAnimation(card_open);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
}
#Override
public void onRefresh() {
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
private void callEvent(int page){
swipe.setRefreshing(true);
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
EventData news = new EventData();
no = obj.getInt(TAG_NO);
news.setId(obj.getString(TAG_ID));
news.setJudul(obj.getString(TAG_JUDUL));
if (!Objects.equals(obj.getString(TAG_GAMBAR), "")) {
news.setGambar(obj.getString(TAG_GAMBAR));
}
news.setDatetime(obj.getString(TAG_TGL));
news.setIsi(obj.getString(TAG_ISI));
// adding news to news array
eventList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
activity_menu_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/meet_buddies"
android:layout_width="fill_parent"
android:drawableLeft="#drawable/ic_profil_w"
android:background="#color/ijo"
android:textColor="#android:color/background_light"
android:layout_height="wrap_content"
android:padding="15dp"
android:onClick="meet"
android:layout_marginTop="70dp"
android:text="Meet Buddies"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/upcoming"
android:layout_width="170dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Notification"
android:layout_marginTop="135dp" />
<Button
android:id="#+id/myshared"
android:layout_width="190dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="135dp"
android:text="My Shared"
/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:stateListAnimator="#null"
android:src="#drawable/ic_plus_w"
app:backgroundTint="#color/colorAccent"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="130dp"
android:stateListAnimator="#null"
android:layout_marginRight="#dimen/fab_margin"
android:visibility="invisible"
android:src="#drawable/ic_menu_camera"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="140dp"
android:layout_marginRight="75dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Event" />
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_beranda"
android:visibility="invisible"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="70dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Homestay" />
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="198dp" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_marginTop="222dp"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_event"
android:layout_width="wrap_content"
android:layout_height="330dp"
android:divider="#null"
android:dividerHeight="2dp"
android:layout_marginTop="222dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
i've tried, how can i fix it ? anyone please help me. thanks.
Anyone else having similar problem. It appears the order in the XML matters too.
I had my NavigationView and after it I had a layout included and I couldn't click an item on the NavigationView.
After I switched them, so that my layout was being included AND THEN AFTER IT I had my NavigationView, it worked ...
this adapter.java
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataModel> item;
public Adapter(Activity activity, List<DataModel> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_buddies, null);
TextView txt_nama = (TextView) convertView.findViewById(R.id.custom_list_item_text1);
txt_nama.setText(item.get(position).getNama());
return convertView;
}
}
You need to create this type of your layout xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
</android.support.v4.widget.DrawerLayout>
In FrameLayout you need to replace all fragment one by one like
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Note: You can write your Coordinator layout and other in fragment itself, may be helpful for you.

Viewpager in Dialog?

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>
Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.
Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>

how can i add an image header to my navigation drawer layout

how can i add an image header to my navigation drawer layout like this one. the problem i now have is that every listitem has it's own icon but the header image is also printed on every item.
this is what i want
What i now have is this:
this is what i have now
mainactivity.java
main activity.java
package be.yvandamme.ginlovers.activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.google.android.gms.analytics.GoogleAnalytics;
import be.yvandamme.ginlovers.R;
import be.yvandamme.ginlovers.WebViewAppApplication;
import be.yvandamme.ginlovers.adapter.DrawerAdapter;
import be.yvandamme.ginlovers.fragment.MainFragment;
public class MainActivity extends ActionBarActivity
{
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerListView;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private String[] mTitles;
public static Intent newIntent(Context context)
{
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupDrawer(savedInstanceState);
// init analytics tracker
((WebViewAppApplication) getApplication()).getTracker();
}
#Override
public void onStart()
{
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// action bar menu
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// open or close the drawer if home button is pressed
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// action bar menu behaviour
switch(item.getItemId())
{
case android.R.id.home:
Intent intent = MainActivity.newIntent(this);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration)
{
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
private void setupActionBar()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupDrawer(Bundle savedInstanceState)
{
mTitle = getTitle();
mDrawerTitle = getTitle();
// title list
mTitles = getResources().getStringArray(R.array.navigation_title_list);
// icon list
TypedArray iconTypedArray = getResources().obtainTypedArray(R.array.navigation_icon_list);
Integer[] icons = new Integer[iconTypedArray.length()];
for(int i=0; i<iconTypedArray.length(); i++)
{
icons[i] = iconTypedArray.getResourceId(i, -1);
}
iconTypedArray.recycle();
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerListView = (ListView) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerListView.setAdapter(new DrawerAdapter(this, mTitles, icons));
mDrawerListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View clickedView, int position, long id)
{
selectDrawerItem(position, false);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if(savedInstanceState == null)
{
selectDrawerItem(0, true);
}
}
private void selectDrawerItem(int position, boolean init)
{
String[] urlList = getResources().getStringArray(R.array.navigation_url_list);
String[] shareList = getResources().getStringArray(R.array.navigation_share_list);
Fragment fragment = MainFragment.newInstance(urlList[position], shareList[position]);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerListView.setItemChecked(position, true);
if(!init) setTitle(mTitles[position]);
mDrawerLayout.closeDrawer(mDrawerListView);
}
}
drawer adapter.java
package be.yvandamme.ginlovers.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import be.yvandamme.ginlovers.R;
public class DrawerAdapter extends BaseAdapter
{
private Context mContext;
private String[] mTitleList;
private Integer[] mIconList;
public DrawerAdapter(Context context, String[] titleList, Integer[] iconList)
{
mContext = context;
mTitleList = titleList;
mIconList = iconList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// inflate view
View view = convertView;
if(view == null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, parent, false);
// view holder
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) view.findViewById(R.id.drawer_item_title);
holder.iconImageView = (ImageView) view.findViewById(R.id.drawer_item_icon);
view.setTag(holder);
}
// entity
String title = mTitleList[position];
Integer icon = mIconList[position];
if(title!=null && icon!=null )
{
// view holder
ViewHolder holder = (ViewHolder) view.getTag();
// content
holder.titleTextView.setText(title);
holder.iconImageView.setImageResource(icon);
}
return view;
}
#Override
public int getCount()
{
if(mTitleList!=null) return mTitleList.length;
else return 0;
}
#Override
public Object getItem(int position)
{
if(mTitleList!=null) return mTitleList[position];
else return null;
}
#Override
public long getItemId(int position)
{
return position;
}
public void refill(Context context, String[] titleList, Integer[] iconList)
{
mContext = context;
mTitleList = titleList;
mIconList = iconList;
notifyDataSetChanged();
}
static class ViewHolder
{
TextView titleTextView;
ImageView iconImageView;
}
}
this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/activity_main_drawer"
android:layout_width="#dimen/drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="false"
android:listSelector="#drawable/selector_clickable_item_bg"
android:background="#color/global_bg_front"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
and this my drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/global_spacing_l"
android:gravity="center_vertical"
android:orientation="horizontal"
android:background="?attr/drawerItemBackground">
<ImageView
android:id="#+id/drawer_image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="#drawable/loading" />
<ImageView
android:id="#+id/drawer_item_icon"
android:layout_width="#dimen/global_spacing_m"
android:layout_height="#dimen/global_spacing_m"
android:layout_marginLeft="#dimen/global_keyline_s"
android:layout_marginRight="#dimen/global_spacing_xs"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_below="#+id/drawer_image"/>
<TextView
android:id="#+id/drawer_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/global_keyline_s"
android:textAppearance="#style/TextAppearance.WebViewApp.Body1"
android:layout_below="#+id/drawer_image"/>
</RelativeLayout>
Try by add header view to your listview (header will also scroll in this case), You need to do like this in your MainActivity :
View header = (View) getLayoutInflater().inflate(
R.layout.header_layout, null);
ImageView img=(ImageView)header.findViewById(R.id.imgView);
img.setBackgroundResource(R.drawable.icon);
mainListView.addHeaderView(header);
Or you can use DesignLibrary like here or here.
Add another view in your XML and position it above activity_main_drawer inside your DrawerLayout. The header is probably not supposed to scroll so it shouldn't be in your listview. Also, remove drawer_image from the listview item layout. Since it's not supposed to be in all the items.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<LinearLayout
android:layout_width="#dimen/drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical">
<ImageView
android:id="#+id/drawer_image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="#drawable/loading" />
<ListView
android:id="#+id/activity_main_drawer"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:choiceMode="singleChoice"
android:drawSelectorOnTop="true"
android:fastScrollEnabled="false"
android:listSelector="#drawable/selector_clickable_item_bg"
android:background="#color/global_bg_front"
/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Or use http://developer.android.com/reference/android/support/design/widget/NavigationView.html and add your image as header view.
navView = (NavigationView) findViewById(R.id.navView);
navView.inflateHeaderView(R.layout.myheader)
or in XML
app:headerLayout="#layout/myheader"

Categories