Viewpager not visible when it has any other layout as its sibling - android

Here is main activity layout XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/left"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_toLeftOf="#+id/left"
android:layout_toRightOf="#+id/right"
tools:context=".MainActivity" />
<LinearLayout
android:id="#+id/right"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
Fragment Layout 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" android:orientation="horizontal"
tools:context=".DummySectionFragment" android:background="#color/gray">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity :
package com.example.androidtest;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager(), getApplicationContext());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
}
Fragment :
package com.example.androidtest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
Pager Adapter :
package com.example.androidtest;
import java.util.Locale;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return context.getString(R.string.title_section1).toUpperCase(l);
case 1:
return context.getString(R.string.title_section2).toUpperCase(l);
case 2:
return context.getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Expected : 2 red bars on both sides. ViewPager in the middle.
Whats happening : 2 red bars on both sides. Blank in the middle.
Question : Why ?
EDIT :
I modified the main activity layout XML to the following to get this to work.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/left"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
<android.support.v4.view.ViewPager
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" android:layout_toRightOf="#+id/left"/>
<LinearLayout
android:id="#+id/right"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#color/red"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
Only change is I removed android:layout_toRightOf="#+id/right" and changed layout_width="fill_parent". Fill_parent I understand. By why does removing the other make a difference ?

You have to do two things in main.xml:
Use LinearLayout instead of RelativeLayout for your main.xml with horizontal orientation.
Add android:layout_weight="1" to your View Pager.

Well, your viewPager's width is: android:layout_width="0dip". No wonder is blank in the middle. Try setting it to android:layout_width="match_parent". In this way it will use all space between right and left views.

Related

How to pass data between tabs?

I have one activity and two tabs in that activity Tab1 and Tab2. These are the two fragments. In my Tab1 have an EditText field and a Button field and Tab2 have only one TextView Field.I want to get the value in EditText field in the Tab1 in to TextView field in Tab2 when I click the button in the Tab1 and also get value when swipe Tab1 to Tab2. I also check many websites but did't get any solution. If anyone know it please help me.
MainActivity.java
package reubro.com.fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayout;
ViewPager viewPager;
Tab1 t2;
EditText ed1;
Tab1 t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = new Tab1();
ed1 = (EditText) findViewById(R.id.ed1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab);
viewPager = (ViewPager) findViewById(R.id.pager);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
Pager pager = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(pager);
tabLayout.setOnTabSelectedListener(this);
}
public void onTabSelected(TabLayout.Tab tab){
viewPager.setCurrentItem(tab.getPosition());
// ed1.setText(t1.ed.getText());
// Log.d("cccccc",ed1.getText().toString());
}
public void onTabUnselected(TabLayout.Tab tab) {
}
public void onTabReselected(TabLayout.Tab tab) {
}
}
Tab1.java
package reubro.com.fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by pc84 on 20/1/17.
*/
public class Tab1 extends Fragment {
Button b1;
EditText ed;
String val;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, final Bundle bundle){
View view = inflater.inflate(R.layout.tab1,viewGroup,false);
b1 = (Button) view.findViewById(R.id.btn1);
ed = (EditText) view.findViewById(R.id.ed1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
val = ed.getText().toString().trim();
if(!(val.isEmpty())){
Log.d("inner",val);
Tab2 tab2 = new Tab2();
Bundle bundle = new Bundle();
bundle.putString("val",val);
tab2.setArguments(bundle);
Toast.makeText(getActivity(),"This is value: "+val,Toast.LENGTH_LONG).show();
}
}
});
return view;
}
}
Tab2.java
package reubro.com.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by pc84 on 20/1/17.
*/
public class Tab2 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle){
View view = inflater.inflate(R.layout.tab2,viewGroup,false);
tv = (TextView) view.findViewById(R.id.tv1);
Bundle bundle1 = this.getArguments();
if (bundle1 != null){
String val = bundle1.getString("val");
tv.setText(val);
Log.d("tttttt",val);
}
return view;
}
}
Pager.java
package reubro.com.fragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by pc84 on 20/1/17.
*/
public class Pager extends FragmentStatePagerAdapter {
int tabCount;
public Pager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/tab"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ed1"
android:hint="Enter something"
android:layout_margin="20dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:id="#+id/btn1"
android:layout_below="#+id/ed1"
android:text="Send to Next Fragment"
android:textAllCaps="false"/>
</RelativeLayout>
tab2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab2"
android:gravity="center"/>
</RelativeLayout>
You can place your data into a Singleton referenced both into Tab1 and Tab2.
A Singleton is a programming pattern that let you to use always the same and the only one instance of a class.
This is an example:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Take a look here to have a more detailed description:
Use ViewModel as a parent data sharing in the parent activity so you can use the same context as viewLifeCycleOwner so you can easily handle the data view and data
To pass data from one tab to another, you can either send a broadcast or if you don't want to broadcast then first pass it to activity through callback then from activity to tab2.
You try to use BroadcastReceiver.
In Tab1 : you send broadcast with data
In Tab2 : you get data from broadcast and set page index
You Can use Live Data object with View Model You can Implement it easily with new Android Architecture.
Doc : https://developer.android.com/topic/libraries/architecture/livedata
No need to EventBus Anymore and Interface for getting LiveData.
I've encountered a similar scenario and came up with the following:
Have the MainActivityViewModel hold any data you may need, and set
it accordingly when the event you are interested in is triggered.
You can then trigger the navigation to the destination tab
programmatically(even if you are using the multiple-stack workaround
used here
https://github.com/googlesamples/android-architecture-components/tree/master/NavigationAdvancedSample),
and have it get any information it may need from the
MainActivityViewModel.
As soon as the information is read, set it to null so it won't be
used again by mistake. You should also have a default behavior, for
when the tab comes up for other reasons, and that variable is null.
Honestly, I'm not sure if by doing this I've gone against some best practices or something, but it has proven useful, and doesn't feel too "hacky".
if your willing to wait until the tab is resumed:
it can be done like this: in your main activity navigation host have a function like this:
fun moveToTabPosition(tabPosition: Int, bundle: Bundle?) {
myFragment?.arguments?.let { it.putAll(bundle) } ?: run { myfragment?.arguments = bundle }
binding.tablayout.setSelectedTab(tabPosition)
binding.yourViewPager.currentItem = tabPosition
}
then just call that with your new bundle updates.
important: in onResume of each tab fragment have a function called updateBundle() and parse the arguments you want again.
the key here is the the arguments have a method called putAll
UPDATE: I want to avoid putAll now ...i notice after Android N it cannot allow to add values to the arguments after the fragment is attached. During QA testing it passed but some users had this issue so had to remove this call.
i got an error on some devices of: java.lang.UnsupportedOperationException : ArrayMap is immutable
Now im in favor of a common interface to call to update the set the arguments data. it would take a bundle as param.

Tab Activity Does Not Work, Causes App to Crash

Hello I am new to android, I am currently trying to navigate from my MainActivity to a TabbedActivity. I created a new TabbedActivity using the default Tabbed Activity template in the Gallery in Android Studio.
However after the files were created, I checked the code and saw that many lines of code used in creating the Activity were cross out, meaning they were deprecated.
I tried running the app, it worked until I tried to navigate to this Tabbed Activity then it crashed and threw an error in my Android Monitor.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxx.eventmanager/com.xxxxxx.eventmanager.EventDetailsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.xxxxxx.eventmanager.EventDetailsActivity.onCreate(EventDetailsActivity.java:42)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
This is my Tabbed Activity named EventDetailsActivity. I have not added any custom code or made any changes to the default code that was generated on create:
package com.xxxxxx.eventmanager;
import android.app.Activity;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
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.widget.TextView;
public class EventDetailsActivity extends Activity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_event_details, 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);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_event_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I am new to both Java and Android and quite perplexed by this.
try to change this line
final ActionBar actionBar = getActionBar();
TO
final ActionBar actionBar = getSupportActionBar();
use extends AppCompatActivity and use use the toolbar as..
private void setup_tabs(){
pager = (CustomViewPager)findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(3);
adapter = new Tabs_Pager_adapter(getSupportFragmentManager(),this);
pager.setAdapter(adapter);
pager.setPagingEnabled(true);
// Title.setText(adapter.getPageTitle(pager.getCurrentItem()));
tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Respondents"));
tabLayout.addTab(tabLayout.newTab().setText("History"));
tabLayout.setupWithViewPager(pager);
}
private void setupToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar != null)
setSupportActionBar(toolbar);
// Show menu icon
final ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowTitleEnabled(false);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
And in your layout..
<LinearLayout
android:layout_weight=".75"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"/>
<your.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And this the theme..
<style name="Base.Theme.your_theme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary</item>
<item name="colorPrimaryDark">#color/my_primary_dark</item>
<item name="colorAccent">#color/my_accent</item>
</style>
Use the app compat library with android support library... and with design support library.. it is awesome. use the tooolbar layout in your layout.xml
and set the theme with appcompat with no actionbar.
How I treat with toolbar in my app (for example).
In my activity layout xml file:
<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"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<!-- more xml code below -->
Content of toolbat.xml:
<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/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/PopupMenuStyle"
android:background="#color/bar_color">
<!-- arbitrary components are in toolbar -->
</android.support.v7.widget.Toolbar>
Now I prepared for set up the toolbar in my app. In onCreate method I have to use this code before using toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
Since that moment I can use getSupportActionBar() and it will return correct result.
In your case you may use setActionBar(toolbar) instead of setSupportActionBar(toolbar) and <android.widget.Toolbar instead of <android.support.v7.widget.Toolbar in your layout file.

Design two tabs within activity after putting some views in that activity

I am a newbie in Android, how can I do something like that.
I extend TabActivity when to create Tabs like this but without that header.
If you want to implement the view you post here ,you can code the view by yourself:
the header is in the top ,and below the header ,a TabHost is needed ,below the TabHost,you put a viewpager contains two fragments to display your data,you can control your viewpager with method setCurrentItem when you click tabs.
Try this code
MainActivity
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.CirclePageIndicator;
public class LauncherActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
pager.setAdapter(new GuidePagerAdapter(getSupportFragmentManager()));
indicator.setViewPager(pager);
}
}
ativity_main
<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"
android:background="#drawable/background"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80000000"
android:orientation="vertical" >
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp" />
</LinearLayout>
</LinearLayout>
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class GuidePagerAdapter extends FragmentStatePagerAdapter {
public GuidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
if (pos == 0)
return new Fragment1();
else
return new Fragment2();
}
#Override
public int getCount() {
return 2;
}
}
You can add two tabs on main_activity and on click of tab change the fragment in adapter.

Android viewpager inside dialogfragment, app crashed with no view found for id using API 17

for the issue in question. Tried Searching for solutions and says getChildFragmentManager/getSupportFragmentManager should be used, but the problem is even with updated android sdk lib using the android support v13 (which has v4) installed, Eclipse Luna still cannot recognize getChildFragmentManager/getSupportFragmentManager. I also tried importing the support.app.v4 namespace but that will only make the ScreenSlidePagerAdapter's FragmentManager throw a type error.
DialogFragment Class which contains the view pager:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
public class EnlargeItemPicture extends DialogFragment {
/**
* The number of pages to show in the view slider
*/
private static int NUM_PAGES = 1; // [Temp] set the total page number according to total items under current selected category instead next time
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager pager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter pagerAdapter;
private View customDialogView;
private String imagePath;
private String itemName;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// instead of inflating the activity with imageview only, inflate the viewpager activity here
customDialogView = inflater.inflate(R.layout.item_pager, null);
// Instantiate a ViewPager and a PagerAdapter.
pager = (ViewPager) customDialogView.findViewById(R.id.pager);
pagerAdapter = new ScreenSlidePagerAdapter(super.getFragmentManager());
pager.setAdapter(pagerAdapter);
/**
* Inflate and set the layout for the dialog
* Pass null as the parent view because its going in the dialog layout
* customDialogView = inflater.inflate(R.layout.dialog_item_picture, null);
* ImageView img = (ImageView) customDialogView.findViewById(R.id.enlargepicture);
* img.setImageBitmap(BitmapFactory.decodeFile(imagePath));
*/
builder.setView(customDialogView)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
public EnlargeItemPicture(String picturePath, String itemName)
{
imagePath = picturePath;
this.itemName = itemName;
}
/**
* A simple pager adapter that represents n objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageItemViewFragment.create(position, "");
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePageItemViewFragment Class that holds the fragment to be inserted to viewpager:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageItemViewFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The argument key for the item Title this fragment represents.
*/
public static final String ARG_ITEM_TITLE = "item_title";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int pageNumber;
private String itemTitle;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number and Title.
*/
public static ScreenSlidePageItemViewFragment create(int pageNumber, String itemTitle) {
ScreenSlidePageItemViewFragment fragment = new ScreenSlidePageItemViewFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putString(ARG_ITEM_TITLE, itemTitle);
fragment.setArguments(args);
return fragment;
}
/**
* Factory method for this fragment class. Constructs a new fragment.
*/
public ScreenSlidePageItemViewFragment()
{ }
/**
* Gets the arguments and pass to this properties
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
itemTitle = getArguments().getString(ARG_ITEM_TITLE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.item_page_view, container, true);
/// TODO: add listeners to each views here
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return pageNumber;
}
/**
* Returns the item title represented by this fragment object.
*/
public String getItemTitle(){
return itemTitle;
}
}
Here is the XML file for layout with viewpager:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Here is the XML file for layout that will be inserted to viewpager:
<?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="wrap_content"
android:orientation="vertical"
android:id="#+id/content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/itemimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/itemDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/minusbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="-" />
<Button
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusbtn"
android:text="+" />
<TextView
android:id="#+id/itemTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/addbtn"
android:layout_alignBottom="#+id/addbtn"
android:layout_toLeftOf="#+id/addbtn"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
I'm at lost here, or perhaps i had it implemented wrong? or something that i had missed?
Plenty of Thanks in Advance!
It may not be an answer in a way, at least it solve one of the causes which gives a new type of exception in which i will post another question if i cannot resolved it with answers from similar problems. The one that got resolved here is I am now able to use the getChildFragmentManager and getSupportFragmentManager function and the answer can be found here: Eclipse Android missing getSupportedFragmentManager and getChildFragmentManager.
I think you should use:
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
Instead of:
Dialog onCreateDialog(Bundle savedInstanceState);
It's helped for me.
Also, check out this link:
fragments in viewpager, no view found error

I can't get ViewPageIndicator to swipe

i have created a new project and included the HoloEveryWhere library. Then I decided to add the ViewPageIndicator.
I copied all the code from ViewPageIndicator sample but it didn't work.
I tried using SherlockFragment but that didn't work either.
So I removed HoloEveryWhere from my project but apparently that wasn't the problem cause it still doesn't swipe.
edit:
this is my 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=".MainActivity" >
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
you see, i just copied the two tags from the samples.
this is the main.java:
package com.example.test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentPagerAdapter adapter = new GoogleMusicAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
}
class GoogleMusicAdapter extends FragmentPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length];
}
#Override
public int getCount() {
return CONTENT.length;
}
}
}
Your layout is the source of your difficulty.
If you are going to use RelativeLayout, you need to specify where the widgets inside the RelativeLayout go. By default, they all go in the upper-left corner, and later children (your ViewPager) float over top of earlier children (your TabPageIndicator) on the Z axis. Hence, with your current layout, the user cannot touch your TabPageIndicator.
Either switch to a vertical LinearLayout or use the appropriate attributes (e.g., android:layout_below) to organize your widgets in the RelativeLayout so that they do not overlap.
Hierarchy View is a useful tool for helping you identify this sort of problem.

Categories

Resources