I'm creating Recycler View.
Here is MainActivity Code:
package com.example.nemes.myapplication;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private List<Movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private MoviesAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new MoviesAdapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
// set the adapter
recyclerView.setAdapter(mAdapter);
prepareMovieData();
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);
}
private void prepareMovieData() {
Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");
movieList.add(movie);
movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");
movieList.add(movie);
movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
movieList.add(movie);
movie = new Movie("Shaun the Sheep", "Animation", "2015");
movieList.add(movie);
movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");
movieList.add(movie);
movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");
movieList.add(movie);
movie = new Movie("Up", "Animation", "2009");
movieList.add(movie);
movie = new Movie("Star Trek", "Science Fiction", "2009");
movieList.add(movie);
movie = new Movie("The LEGO Movie", "Animation", "2014");
movieList.add(movie);
movie = new Movie("Iron Man", "Action & Adventure", "2008");
movieList.add(movie);
movie = new Movie("Aliens", "Science Fiction", "1986");
movieList.add(movie);
movie = new Movie("Chicken Run", "Animation", "2000");
movieList.add(movie);
movie = new Movie("Back to the Future", "Science Fiction", "1985");
movieList.add(movie);
movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");
movieList.add(movie);
movie = new Movie("Goldfinger", "Action & Adventure", "1965");
movieList.add(movie);
movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
#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_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
And Adapter class:
package com.example.nemes.myapplication;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private List<Movie> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
genre = (TextView) view.findViewById(R.id.genre);
year = (TextView) view.findViewById(R.id.year);
}
}
public MoviesAdapter(List<Movie> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Movie movie = moviesList.get(position);
holder.title.setText(movie.getTitle());
holder.genre.setText(movie.getGenre());
holder.year.setText(movie.getYear());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
My problem is - when i launch app all okay, I see movies and info
Here is screen:
But when I scroll activity, I have this
It turns bigger.
Where is error?
Thank's for help.
UPDATE
Here is movie_list_row layout
<?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="match_parent"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/genre"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/year"
android:textColor="#color/year"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content" />
</RelativeLayout>
In your movie_list_row, change your RelativeLayout's height to
android:layout_height="wrap_content"
Or set an exact value like 100dip.
In your movie_list_row just change the layout_height of relative layout
<?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:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
Related
I am trying to replace home fragment with gallery fragment and vice versa in the default navigation drawer from Android Studio. This is the main class:
package com.example.navdrawer;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
This is the home fragment class:
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.navdrawer.R;
import com.example.navdrawer.ui.gallery.GalleryFragment;
public class HomeFragment extends Fragment {
Button button;
TextView textView = null;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
textView = root.findViewById(R.id.text_home);
textView.setText("This is home fragment");
button = root.findViewById(R.id.home_button);
return root;
}
public void onClick(View v) {
//respond to clicks
if (v.getId() == R.id.home_button) {
GalleryFragment frag = new GalleryFragment();
FragmentManager ft = getFragmentManager();
FragmentTransaction fragmentTransaction =ft.beginTransaction();
fragmentTransaction.replace(R.id.home, frag);
// ft.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
The gallery fragment is simillar with the home fragment:
package com.example.navdrawer.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.navdrawer.R;
import com.example.navdrawer.ui.home.HomeFragment;
public class GalleryFragment extends Fragment {
Button button;
TextView textView = null;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
textView = root.findViewById(R.id.text_gallery);
textView.setText("This is gallery fragment");
button = root.findViewById(R.id.gallery_button);
return root;
}
public void onClick(View v) {
//respond to clicks
if (v.getId() == R.id.gallery_button) {
HomeFragment frag = new HomeFragment();
FragmentManager ft = getFragmentManager();
FragmentTransaction fragmentTransaction =ft.beginTransaction();
fragmentTransaction.replace(R.id.gallery, frag);
// ft.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
And I've got this xml for the home fragment, which is simillar with the xml from the gallery fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:id="#+id/home"
android:screenOrientation="portrait"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_home"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/home_button"
android:layout_centerHorizontal="true"
android:layout_below="#+id/text_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/replace1" />
</RelativeLayout>
</ScrollView>
I don't know why it's not working.
I've found the answer from this post: link
For navigation between fragments, all I had to do was to implement this method in the "onCreateView" function:
button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.nav_gallery, null));
Another method is:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Navigation.findNavController(view).navigate(R.id.nav_gallery);
}
});
I still don't know how to navigate between fragments using a conditional "if, else" statement, inside a function, maybe this will imply another type of "action listening"...
The default template uses the Navigation component which means you don't manually do FragmentTransactions. Instead, as per the documentation, you'd add your GalleryFragment to your navigation XML file (under res/navigation) then call navigate() to go to that destination, replacing the screen you're currently on.
Greeting everyone, I'm trying to make an app with a navigational drawer and capable of having selectable contacts in one of the drawers but it keeps crashing.The app I built worked great for displaying the contact. When I started trying to implement the clicking on the contacts to navigate to another Fragment which would have the contact info, The App Wouldn't launch. Any help, even to point me in the right direction is greatly appreciated.
Project File
Main Activity Java Fragment
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.example.v1z0.assignments.Utils.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Log.d(TAG, "onCreate: started");
initImageLoader();
init();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void initImageLoader()
{
UniversalImageLoader universalImageLoader = new UniversalImageLoader(MainActivity.this);
ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
#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_activity_faculty) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,
new ViewContactsFragment()).commit();
} else if (id == R.id.nav_second_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new SecondFragment()).commit();
} else if (id == R.id.nav_third_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new ThirdFragment()).commit();
} else if (id == R.id.nav_fourth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new FourthFragment()).commit();
} else if (id == R.id.nav_fifth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new FifthFragment()).commit();
} else if (id == R.id.nav_sixth_layout) {
getFragmentManager().beginTransaction().replace(R.id.content_frame,
new SixthFragment()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void init()
{
{
ViewContactsFragment fragment = new ViewContactsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
My Contact Fragment
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ContactFragment extends Fragment {
private static final String TAG = "ContactFragment";
public ContactFragment(){
super();
setArguments(new Bundle());
}
private Toolbar toolbar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact, container, false);
toolbar = (Toolbar) view.findViewById(R.id.contactToolbar);
Log.d(TAG, "onCreateView: started");
//Toolbar Pre-req//
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
//Go Back//
ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
ivBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked back arrow");
getActivity().getSupportFragmentManager().popBackStack();
}
});
//Go To Edit//
ImageView ivEdit = (ImageView) view.findViewById(R.id.ivEdit);
ivEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked edit");
EditContactFragment fragment = new EditContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment" + getString(R.string.edit_contact_fragment));
transaction.commit();
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.contact_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.menuitem_delete:
Log.d(TAG, "onOptionsItemSelected: deleting contact");
}
return super.onOptionsItemSelected(item);
}
}
Also the View Contact Fragment holding the contact information
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import com.example.v1z0.assignments.Models.Contact;
import com.example.v1z0.assignments.Utils.CustomListAdapter;
public class ViewContactsFragment extends Fragment {
private static final String TAG = "FirstFragment";
//images
private String testImageURL = "cis.ncu.edu.jm/images/faculty/man.jpg";
private String hgraham = "cis.ncu.edu.jm/images/faculty/hgraham.jpg";
private String dmitchell = "cis.ncu.edu.jm/images/faculty/dmitchell.png";
private String mnarayana = "cis.ncu.edu.jm/images/faculty/mnarayana.jpg";
private String hosborne = "cis.ncu.edu.jm/images/faculty/hosborne.jpg";
private String mreid = "cis.ncu.edu.jm/images/faculty/mreid.jpg";
private String esmall = "cis.ncu.edu.jm/images/faculty/esmall.jpg";
private String hsmith = "cis.ncu.edu.jm/images/faculty/hsmith.jpg";
private String ktooma = "cis.ncu.edu.jm/images/faculty/ktooma.jpg";
//widgets etc
private static final int STANDARD_APPBAR = 0;
private static final int SEARCH_APPBAR = 1;
private int mAppBarState;
private AppBarLayout viewContactsBar, searchBar;
private CustomListAdapter adapter;
private ListView contactsList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewcontacts, container, false);
viewContactsBar = (AppBarLayout) view.findViewById(R.id.viewContactsToolbar);
searchBar = (AppBarLayout) view.findViewById(R.id.searchtoolbar);
contactsList = (ListView) view.findViewById(R.id.contactsList);
Log.d(TAG, "onCreate: started");
setAppBarState(STANDARD_APPBAR);
setupContactsList();
//add contact navigation//
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fabAddContact);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked fab");
}
});
//search contact navigation//
ImageView ivSearchContact = (ImageView) view.findViewById(R.id.ivSearchIcon);
ivSearchContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked search");
toggleToolBarState();
}
});
ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
ivBackArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked back arrow");
toggleToolBarState();
}
});
return view;
}
private void setupContactsList()
{
final ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("Mr. Sheldon Glenn ", "(876) 963-7281", "work", "sheldon.glenn#ncu.edu.jm ", testImageURL));
contacts.add(new Contact("Mr. Hamlet Graham ", "(876) 963-7278", "work", "hamlet.graham#ncu.edu.jm ", hgraham));
contacts.add(new Contact("Mr. Oche Magbegor ", "(876) 963-7280", "work", "oche.magbegor#ncu.edu.jm ", testImageURL));
contacts.add(new Contact("Mr. Damion Mitchell ", "(876) 963-7285", "work", "damion.mitchell AT ncu.edu.jm ", dmitchell));
contacts.add(new Contact("Mr. Melvin Narayana ", "(876) 963-7279", "work", "melvin.narayana#ncu.edu.jm", mnarayana));
contacts.add(new Contact("Mr. Henry Osborne ", "(876) 963-7282", "work", "Henry.Osborne#ncu.edu.jm ", hosborne));
contacts.add(new Contact("Mr. Marlon Richards ", " (876) 963-7276", "work", "marlon.richards#ncu.edu.jm", testImageURL));
contacts.add(new Contact("Mrs. E. Beverley Small ", "(876) 963-7276", "work", "esmall#ncu.edu.jm ", esmall));
contacts.add(new Contact("Mr. Halzen Smith ", "(876) 963-7284", "work", "hsmith#ncu.edu.jm ", hsmith));
contacts.add(new Contact("Mr. Keron Tooma ", " (876) 963-7283", "work", "keron.tooma#ncu.edu.jm ", ktooma));
adapter = new CustomListAdapter(getActivity(), R.layout.layout_contactslistitem, contacts, "http://");
contactsList.setAdapter(adapter);
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
Log.d(TAG, "onClick: navigating to contact" + (R.string.contact_fragment));
ContactFragment fragment = new ContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment" + getString(R.string.contact_fragment));
transaction.commit();
}
});
}
private void toggleToolBarState()
{
Log.d(TAG, "toggleToolBarState: toggling AppBatState");
if (mAppBarState == STANDARD_APPBAR)
{
setAppBarState(SEARCH_APPBAR);
}
else
{
setAppBarState(STANDARD_APPBAR);
}
}
#Override
public void onResume() {
super.onResume();
setAppBarState(STANDARD_APPBAR);
}
private void setAppBarState(int state)
{
Log.d(TAG, "setAppBarState: changing app bar state to" + state);
mAppBarState = state;
if (mAppBarState == STANDARD_APPBAR)
{
searchBar.setVisibility(View.GONE);
viewContactsBar.setVisibility(View.VISIBLE);
//keyboard hide//
View view = getView();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
try
{
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}catch (NullPointerException e)
{
Log.d(TAG, "setAppBarState: NullPointerException" + e.getMessage());
}
}
else if (mAppBarState == SEARCH_APPBAR)
{
viewContactsBar.setVisibility(View.GONE);
searchBar.setVisibility(View.VISIBLE);
//keyboard show//
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
}
LogCat Error
--------- beginning of crash
2018-10-14 01:48:19.869 7041-7041/com.example.v1z0.assignments E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.v1z0.assignments, PID: 7041
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.v1z0.assignments/com.example.v1z0.assignments.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f080055 (com.example.v1z0.assignments:id/fragment_container) for fragment ViewContactsFragment{dcf4537 #0 id=0x7f080055}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f080055 (com.example.v1z0.assignments:id/fragment_container) for fragment ViewContactsFragment{dcf4537 #0 id=0x7f080055}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1422)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
at android.app.Activity.performStart(Activity.java:7029)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
XML Fragments
Solo Contact Page
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayout1">
<include layout="#layout/snippet_contacttoolbar"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/relLayout1"
android:id="#+id/relLayout2">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
app:civ_border_color="#color/black"
app:civ_border_width="1dp"
android:id="#+id/contactImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/contactImage"
android:layout_marginTop="30dp"
android:textSize="30sp"
android:textColor="#color/black"
android:layout_marginStart="30dp"
android:id="#+id/tvName" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tvName"
android:id="#+id/lvContactProperties">
</ListView>
</RelativeLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
View Contact List Fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/first">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/relLayout1">
<include layout="#layout/snippet_searchtoolbar"/>
<include layout="#layout/snippet_viewcontactstoolbar"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/relLayout1">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/contactsList"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/textNoContacts"
android:textColor="#color/black"
/>
</RelativeLayout>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:elevation="10dp"
app:fabSize="normal"
app:rippleColor="#color/colorAccent"
android:src="#drawable/ic_person_add"
android:id="#+id/fabAddContact"/>
</android.support.design.widget.CoordinatorLayout>
Edit Page
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>
I apologize for the lengthy question
In your init() methond of MainActivity class file, you reference incorrect resource id.
private void init()
{
{
ViewContactsFragment fragment = new ViewContactsFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, fragment);//not R.id.fragment_container
transaction.addToBackStack(null);
transaction.commit();
}
}
In addition to navylover answer. I also changed Fragment_container in my ViewContactFragment and it worked
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
{
Log.d(TAG, "onClick: navigating to contact" + (R.string.contact_fragment));
ContactFragment fragment = new ContactFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(getString(R.string.edit_contact_fragment));
Log.d(TAG, "onClick: fragment contentFrame" );
transaction.commit();
}
});
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();
}
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"
I have a Problem with switching Fragments in the default Navigation Drawer
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
package flo.nawigator;
#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, "HILFE:" +
" An der oberen linken Ecke, findest Du Drei Striche mit dem sich ein Menü öffnen lässt", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public 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();
Fragment fragment;
if (id == R.id.nav_gallery) {
} else if (id == R.id.Experimente) {
} else if (id == R.id.nav_formeln) {
} 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;
}
}
ContentMain.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView android:text="#string/TextViewIntro" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elegantTextHeight="false"
android:gravity="top|center"
android:textColor="#000000"
android:textSize="#dimen/abc_text_size_title_material"
android:id="#+id/TextViewIntro"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="53dp"
android:src="#android:drawable/ic_menu_help" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#+id/TextViewIntro"
android:layout_alignParentEnd="true"
android:id="#+id/mainFrame"></FrameLayout>
BlankFragment.java
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
package flo.nawigator;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fraglayoutv = inflater.inflate(R.layout.fragment_blank, null);
fragbtn1 = (Button) fraglayoutv.findViewById(R.id.buttonfrag1);
fragbtn1.setOnClickListener(this);
return fraglayoutv;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonfrag1: {
Toast.makeText(getActivity(), "Button gedrückt!!", Toast.LENGTH_SHORT).show();
}
}
}
I have a BlankFragment! How do I Switch to it with Android Navigation Drawer
MainActivity.xml
<include layout="#layout/app_bar_main" 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_main" app:menu="#menu/activity_main_drawer" />
fragment_blank.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" tools:context="flo.nawigator.BlankFragment"
android:id="#+id/fragmentgalerie">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/galeriefragtext"
android:id="#+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Okay!"
android:id="#+id/buttonfrag1"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/textView"
android:layout_marginBottom="217dp" />
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_gallery) {
} else if (id == R.id.Experimente) {
BlankFragment bnlfrgmnt = new BlankFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.mainFrame, bnlfrgmnt).commit();
//do similar for other navigation drawer items to display other fragments.
} else if (id == R.id.nav_formeln) {
} 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;
}