Toolbar content not appearing despite fragment content appearing - java

I'm trying to show the necessary content within my toolbar (i.e. the title and back button) but for some reason is doesn't appear but yet the main content within my fragment does. What can be done to resolve this issue?
MapActivity.java
public class MapActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_map);
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imageView);
imageView.setImage(ImageSource.resource(R.drawable.map));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
final Intent intent = NavUtils.getParentActivityIntent(this);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
NavUtils.navigateUpTo(this, intent);
return true;
}
return false;
}
}
FragmentMap.java
public class FragmentMap extends android.support.v4.app.Fragment {
public FragmentMap() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_map, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.actionBar);
toolbar.setBackgroundColor(Color.parseColor("#212121"));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.map) + "</font>"));
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
activity.getSupportActionBar().setDisplayShowHomeEnabled(false);
return v;
}
}
fragment_map.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"
android:id="#+id/fragmentmap" >
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/actionBar"
android:elevation="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetEnd="0dp"
app:contentInsetStart="16dp" >
</android.support.v7.widget.Toolbar>
<com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
</style>
</resources>

Complete Code
MapActivity
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MapActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.actionBar);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.parseColor("#212121"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MapActivityFragment())
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super. onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_map.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"
android:background="#color/whiteColor"
android:id="#+id/fragmentmap" >
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/actionBar"
android:elevation="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetEnd="0dp"
app:contentInsetStart="16dp" >
</android.support.v7.widget.Toolbar>
<LinearLayout
android:id="#+id/container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
styles.xml
<style name="AppThemeNew" parent="Theme.AppCompat.NoActionBar">
</style>
MapActivityFragment.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A placeholder fragment containing a simple view.
*/
public class MapActivityFragment extends Fragment {
public MapActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
getActivity().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + "Hello Toolbar" + "</font>"));
return rootView;
}
}
fragment_map.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_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/whiteColor"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/blackColor"/>
</RelativeLayout>

Add this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_map, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.actionBar);
toolbar.setBackgroundColor(Color.parseColor("#212121"));
//---- changes ---
((MapActivity) getActivity()).setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.map) + "</font>"));
((MapActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MapActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(false);
return v;
}

Related

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

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

Navigation drawer is under other widgets

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;
}
}

Android ViewPager.PagerTransformer Cube animation strange behavior

I am trying to implement a cube animation on my viewPager. The animation looks good on the emulator and a Samsung S8 device, but on Huawei P10 Android 7.0 it looks like in the image below:
I don't understand why the image is cropped on my Huawei device. Below is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="ro.helpproject.funcode.help.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
view_pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imageView_mario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/black"
android:src="#drawable/mario" />
CubeTransformer.java class
package ro.helpproject.funcode.help;
import android.support.v4.view.ViewPager;
import android.view.View;
public class CubeTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
view.setPivotX(position <= 0 ? view.getWidth(): 0.0f);
view.setRotationY(90f * position);
}
}
MainActivity.java
package ro.helpproject.funcode.help;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyViewPagerAdapter adapter = new MyViewPagerAdapter();
ViewPager pager = findViewById(R.id.pager);
pager.setPageTransformer(true, new CubeTransformer());
pager.setAdapter(adapter);
}
protected class MyViewPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
ImageView imageView = (ImageView) inflater.inflate(R.layout.view_pager_item, container, false);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
How can I fix the issue?
imageview.setAdjustViewBounds(true);
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_XY);
update.....
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imageView_mario"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY"
android:background="#android:color/black"
android:src="#drawable/mario" />
The best way to achieve this is to add a parent to your imageView as follows:
<?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="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/imageView_mario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:src="#drawable/mario" />
</LinearLayout>
Then in instantiateItem replace imageView with the LinearLayout:
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.view_pager_item, container, false);
container.addView(linearLayout);
return linearLayout;
}
This should work properly.
The reason that your solution does not work is that the viewpager tries to fill it's "pages" with the imageview that you provide from your xml, and so it is stretched and has unexpected behaviour.

How to add New Activity from Android GridView onItemClick?

Check this image sample i have done it Material Design Gridview Image
I have done the same Material Design for grid view Activity on my app, i like to add the onItemClick to new Activity,
I don't know how to do this , please give the brief explanation for the solution
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/appbar_layout"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_android_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="#dimen/expanded_toolbar_title_margin_start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/code"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:id="#+id/nestedscrollview"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
res/layout/gridview_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_gridview_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<com.andexert.library.RippleView
android:id="#+id/more"
rv_centered="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:rv_color="#fff"
app:rv_rippleDuration="200">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:orientation="vertical">
<ImageView
android:id="#+id/gridview_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/gridview_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/grid_image"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Grid View Item"
android:textColor="#444"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</com.andexert.library.RippleView>
</LinearLayout>
src/MainActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.GridView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
src/CustomAndroidGridViewAdapter.java
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;
/**
* Created by HP on 5/11/2016.
*/
public class CustomAndroidGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] string;
private final int[] Imageid;
public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.string = string;
}
#Override
public int getCount() {
return string.length;
}
#Override
public Object getItem(int p) {
return null;
}
#Override
public long getItemId(int p) {
return 0;
}
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
} else {
grid = (View) convertView;
}
return grid;
}
}
PLease give me the solution for call another Actvivty when mouse click on Image (Image 1, Image 2, etc) in Gridview this
Replace your method with mine
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourActivity.class);
context.startActivity(intent);
}
});
} else {
grid = (View) convertView;
}
return grid;
}
here is the code to go another activity after click on every image.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(1))){
Intent intent=new Intent(MainActivity.this,SecoundActivity.class);
intent.putExtra("image",gridViewImages[position]);
startActivity(intent);
}
else if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(2))){
Intent intent2=new Intent(MainActivity.this,ThirdActvity.class);
intent2.putExtra("image2",gridViewImages[position]);
startActivity(intent2);
}
//Like this create activites how many images are there in gridViewImages[]array.you have 9 images so create nine activities..you have to send the url in every activity from one activity to another activity according to your requirement
}
});
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
create SecoundActivity.class
public class SecoundActivity extends AppCompactActivity{
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
int position = intent.getExtras().getInt("image");
setContentView(R.layout.secound_view);
image=(ImageView) findViewById(R.id.image);
image.setImageResource(position);
}
}
then Finally create the secound_view.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"
android:padding="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_horizontal_margin">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/image"
/>
</LinearLayout>
After 10 seconds in Google...
Starting Another Activity
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
And Click Listener/Event
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Item Clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
In your MainActivity onCreate method, add an OnItemClick listener for the GridView:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Your Intent goes here
}
});

Unfortunately <project name> has stopped message

I'm new to android and I'm using Android studio.I have created a basic program with two buttons.But once I started the emulator the app doesn't start.I'm getting a message saying 'Unfortunately -project name- has stopped'. But the code compiled without any error.Here I'm attaching the codes.
AndroidMAnifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.projectdrogo" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.projectdrogo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is my MainActivity.java code
package com.example.projectdrogo;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter;
Button add,subtract;
TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter =0;
add = (Button)findViewById(R.id.bAdd);
subtract=(Button)findViewById(R.id.bSubtract);
textview=(TextView)findViewById(R.id.textView);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
textview.setText("Your Total is "+counter);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter--;
textview.setText("Your Total is "+counter);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Here is my main.xml
<menu 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"
tools:context="com.example.projectdrogo.MainActivity" >
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.projectdrogo.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.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_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.projectdrogo.MainActivity$PlaceholderFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1">
<TextView
android:text="#string/name"
android:textSize="50dp"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/textView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Subtract One"
android:id="#+id/bSubtract"
android:textSize="30dp"
android:layout_gravity="center"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Add One"
android:id="#+id/bAdd"
android:layout_gravity="center"
android:textSize="30dp" />
</LinearLayout>
</RelativeLayout>
Please help me.I'm stuck in this.
Thank you
activity_main.xml does not have a button or textviews. Looks like its in a Fragment Layout
I guess you have a fragment
PlaceholderFragment newFragment = new PlaceholderFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Then in onCreateView of Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
add = (Button)rootView.findViewById(R.id.bAdd);
subtract=(Button)rootView.findViewById(R.id.bSubtract);
textview=(TextView)rootView.findViewById(R.id.name);
...// rest of the code
You have a FrameLayout which is a container. You need to add the fragment to the container. Also the views in activity belong to fragment layout. So you need to initialize the same in onCreateView as suggested.
Edit:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PlaceholderFragment newFragment = new PlaceholderFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Then
public static class PlaceholderFragment extends Fragment {
int counter;
Button add,subtract;
TextView textview;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
add = (Button)rootView.findViewById(R.id.bAdd);
subtract=(Button)rootView.findViewById(R.id.bSubtract);
textview=(TextView)rootView.findViewById(R.id.name);
... // rest of the code
return rootView;
}
}

Categories