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"
Related
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;
}
}
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.
In my android project, there are three tabs in the main page. I placed the horizontal recyclerview in the third tab. it works fine for the first time, but when I visit first tab and come back, the horizontal recyclerview gets disappeared. Someone please help me
codes are given below.
Tab3.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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Suggestions" />
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="180dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
</LinearLayout>
recycler_items.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
android:weightSum="4"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3.2"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/coverImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerCrop"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:background="#android:drawable/screen_background_dark_transparent"
android:orientation="vertical">
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="#dimen/text_size"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.8"
android:gravity="center|right"
android:orientation="horizontal">
<ImageView
android:id="#+id/likeImageView"
android:layout_width="#dimen/icon_width"
android:layout_height="#dimen/icon_height"
android:padding="#dimen/icon_padding"
android:src="#drawable/ic_like" />
<ImageView
android:id="#+id/shareImageView"
android:layout_width="#dimen/icon_width"
android:layout_height="#dimen/icon_height"
android:padding="#dimen/icon_padding"
android:src="#drawable/ic_share" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
fragment_horizontal_list_view.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:paddingLeft="#dimen/activity_left_margin"
android:paddingRight="#dimen/activity_right_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Tab3.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Arshad on 09-06-2017.
*/
public class Tab3 extends Fragment {
ListView listView;
listItemAdapterPop listItemAdapter_Pop;
String[] names = {"Hrithik","Ranbir","AkshayKumar","Amir Khan","Shahidi Kapoor"};
String[] type = {"Bollywood actor","Mollywood Actor","Dancer","Playback Singer","DJ"};
int[] images = {R.drawable.index1,R.drawable.index2,R.drawable.index3,R.drawable.index4,R.drawable.index5};
private List<Artists> artistList = new ArrayList<>();
private RecyclerView recyclerView;
private ArtistAdapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab3,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// listView = (ListView)view.findViewById(R.id.listView_pop);
// listItemAdapter_Pop = new listItemAdapterPop(getActivity(),names,images,type);
// listView.setAdapter(listItemAdapter_Pop);
//listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// #Override
//public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Toast.makeText(getActivity(), "you can view the profile of :"+names[i], Toast.LENGTH_SHORT).show();
// }
//});
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new HorizontalListViewFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mAdapter = new ArtistAdapter(artistList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
// set the adapter
recyclerView.setAdapter(mAdapter);
prepareArtistData();
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Artists artist = artistList.get(position);
Toast.makeText(getActivity(), artist.getArtistName() + " is selected!", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
Artists artist = artistList.get(position);
Toast.makeText(getActivity(), artist.getArtistName() + " is long pressed selected!", Toast.LENGTH_SHORT).show();
}
}));
}
public void prepareArtistData(){
for(int i=0;i<names.length;i++){
Artists artist = new Artists(names[i], type[i], images[i]);
artistList.add(artist);
}
mAdapter.notifyDataSetChanged();
}
}
HorizontalListViewFragment.java
package com.example.majedhussain.loginsample;
/**
* Created by anonymous on 11/4/16.
*/
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HorizontalListViewFragment extends Fragment {
ArrayList<Artists> listitems = new ArrayList<>();
RecyclerView MyRecyclerView;
String ArtistsS[] = {"Hrithik","Ranbir","AkshayKumar","Amir Khan","Shahidi Kapoor"};
int Images[] = {R.drawable.index1,R.drawable.index2,R.drawable.index3,R.drawable.index4,R.drawable.index5};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listitems.clear();
for(int i =0;i<ArtistsS.length;i++){
Artists item = new Artists();
item.setArtistName(ArtistsS[i]);
item.setImageResourceId(Images[i]);
item.setIsfav(0);
item.setIsturned(0);
listitems.add(item);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_horizontal_list_view, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
if (listitems.size() > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(listitems));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<Artists> list;
public MyAdapter(ArrayList<Artists> Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getArtistName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
}
#Override
public int getItemCount() {
return list.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites", Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites", Toast.LENGTH_SHORT).show();
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' + getResources().getResourceEntryName((int)coverImageView.getTag()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
}
});
}
}
}
Artists.java
package com.example.majedhussain.loginsample;
/**
* Created by MAJED HUSSAIN on 14-06-2017.
*/
public class Artists {
String artistName;
String desc;
int imageResourceId;
int isfav;
int isturned;
public Artists(String artistName, String desc, int imageResourceId) {
this.artistName = artistName;
this.desc = desc;
this.imageResourceId = imageResourceId;
}
public Artists() {
}
public void setDesc(String desc){
this.desc = desc;
}
public String getDesc() {
return desc;
}
public int getIsturned() {
return isturned;
}
public void setIsturned(int isturned) {
this.isturned = isturned;
}
public int getIsfav() {
return isfav;
}
public void setIsfav(int isfav) {
this.isfav = isfav;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public int getImageResourceId() {
return imageResourceId;
}
public void setImageResourceId(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
}
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
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;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,TabLayout.OnTabSelectedListener {
private TabLayout tabLayout;
private ViewPager viewPager;
#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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Favourites"));
tabLayout.addTab(tabLayout.newTab().setText("Trending"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(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.
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) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
output images are:
This is the first output in which horizontal list is visible
This is the second output after I visited first tab and came back. now horizontal list is disappeared
I think your fragment is not null:
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new HorizontalListViewFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
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>
I need help on solving an issue with app crashing when i try to set onClickListener on a button (btOK).
This is my MainActivity.java:
package edu.np.ece.mapg.newsweather;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import edu.np.ece.mapg.proj.fragments.TabsPagerAdapter;
import edu.np.ece.mapg.proj.rss.RssItem;
import edu.np.ece.mapg.proj.rss.RssReader;
public class MainActivity extends FragmentActivity {
ViewPager mViewPager;
TabsPagerAdapter mAdapter;
ActionBar mActionBar;
String[] tabStrings = {"Main", "News", "Weather"};
TextView tv;
Button btOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btOK = (Button)findViewById(R.id.btOK);
tv = (TextView)findViewById(R.id.textView1);
btOK.setOnClickListener(asd);
//Initialize
mViewPager = (ViewPager)findViewById(R.id.pager);
mActionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); //Initialize the created adapter class
mViewPager.setAdapter(mAdapter);
mActionBar.setHomeButtonEnabled(false);
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add tabs
for(String tab_name : tabStrings){
mActionBar.addTab(mActionBar.newTab().setText(tab_name).setTabListener(tabListener));
}
mViewPager.setOnPageChangeListener(pageListener);
// MINI PROJ PHASE 2 //
try{
RssReader rssReader = new RssReader("http://news.google.com/news?pz=1&cf=all&ned=en_sg&hl=en&output=rss");
ListView newsListView = (ListView)findViewById(R.id.newsListView);
//Create list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getBaseContext(), android.R.layout.simple_list_item_1, rssReader.getItems());
//Set list adapter for listview
newsListView.setAdapter(adapter);
//Set listview item click listener
newsListView.setOnItemClickListener((OnItemClickListener) new ListListener(rssReader.getItems(), this));
adapter.notifyDataSetChanged();
}
catch(Exception e){
Log.e("SimpleRssReader", e.getMessage());
}
}
View.OnClickListener asd = new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("OK");
}
};
ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// On changing page, make respected tab selected
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {};
#Override
public void onPageScrollStateChanged(int arg0) {};
};
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
#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;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
news_fragment.xml , the place where i set my buttons:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/btOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/newsListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You have
setContentView(R.layout.activity_main);
activity_main.xml does not a have a button with id btOK
Your news_fragment.xml has a button.
So if you initialize button in Activity you get NullPointerException leading to crash.
Its the same for TextView and ListView.
findViewById will look for a view with the id in the current inflated layout.
http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
Change
View.OnClickListener asd = new View.OnClickListener()
to
btOK.OnClickListener(new View.OnClickListener())
Similarly
SetOnPageListener to mViewPager and TabListener to mActionBar
buttonOk and textView1 are in news_fragment.xml, You can fetch these views in fragment where you setting news_fragment.xml ,