I have created ViewPager and tabs. But unfortunately the fragments have added not below the titel of the tabs. I want that the fragment (LoginFragment and ProfleFragment) were located below titles of tabs (Login). How can I do it? Now they look this way (disgusting view):
It's not possible to see textview "username" and texfield for username
How can I cange xml laoyout or add code to locate them correctly?
Here is my code:
profilefragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:contentDescription="#string/photoDesc_en"
android:id="#+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/userInfo"
android:src="#drawable/standarduserphoto" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/userInfo"
android:layout_alignParentRight="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/username_en"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userNameTextView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/email_en"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/emailTextView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/birthdate_en"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/birthDateTextView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gender_en"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/genderTextView"
/>
</LinearLayout>
</RelativeLayout>
activity_fullscreen.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
loginfragment.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="wrap_content"
>
<!-- Log In Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="#string/login_en"/>
<EditText
android:id="#+id/logInTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:singleLine="true"
/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="#string/password_en"/>
<EditText android:layout_width="fill_parent"
android:id="#+id/passwordTextField"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="textPassword"
/>
<!-- Login button -->
<Button android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/login_en"/>
</LinearLayout>
ProfileFragment.java
package com.example.vklogin;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ProfileFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profilefragment, container, false);
return rootView;
}
}
MainActivity.java
package com.example.vklogin;
import com.example.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private Button logIn,logOut;
private EditText passwordField,userNameField;
// Tab titles
private String[] tabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
//LinearLayout userInfoLayout = (LinearLayout) View.inflate(this, R.layout.loginfragment, null);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabs = getResources().getStringArray(R.array.tabViews_en);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
///
private OnClickListener authorizeClick=new OnClickListener(){
#Override
public void onClick(View v) {
//startLoginActivity();
}
};
private void startLoginActivity() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
private void setupUI() {
logIn=(Button)findViewById(R.id.btnLogin);
logIn.setOnClickListener(authorizeClick);
passwordField=(EditText)findViewById(R.id.passwordTextField);
userNameField=(EditText)findViewById(R.id.logInTextField);
}
}
LogInFragment.java
package com.example.vklogin;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LogInFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginfragment, container, false);
return rootView;
}
}
TabsPagerAdapter.java
package com.example.adapter;
import com.example.vklogin.LogInFragment;
import com.example.vklogin.ProfileFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new LogInFragment();
case 1:
// Games fragment activity
return new ProfileFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
AndroidMafiest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vklogin"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.vklogin.MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try removing the activoty's theme from the manifest and see if it works.
Related
I am just doing my Daily practice and I had a Problem. I've created Viewpager on Tab Layout but it not worked.
I don't know why, I am just doing like the tutorial on the internet and spend for this problem 2 days. :/
The Tablayout showing all tabs but not with the view (fragment tab).
I'll thank for any help from you all :))))))))
So, here's what I code,
content_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.ViewPagerActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/content_home_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimaryAlternate"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorPrimary"
app:tabSelectedTextColor="#color/colorPrimary"
app:tabTextColor="#color/colorPrimaryDarkAlternate"
app:tabIconTint="#color/tab_color_selector"
app:tabTextAppearance="#style/tabAllCaps">
<com.google.android.material.tabs.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_waterpark"
android:text="#string/waterpark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_home_black_24dp"
android:text="#string/drypark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_human_male_female"
android:text="#string/facilities" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/content_home_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/content_home_tablayout"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_alignParentBottom="true" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
ViewPagerActivity:
package com.ardityo.android.transeraapps.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.home.tabs.drypark.DryParkFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.facilities.FacilitiesFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.waterpark.WaterParkFragment;
import com.google.android.material.tabs.TabLayout;
public class ViewPagerActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter;
WaterParkFragment waterParkFragment;
DryParkFragment dryParkFragment;
FacilitiesFragment facilitiesFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_home);
viewPager = (ViewPager) findViewById(R.id.content_home_viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.content_home_tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// waterParkFragment=new WaterParkFragment();
// dryParkFragment=new DryParkFragment();
// facilitiesFragment=new FacilitiesFragment();
// adapter.addFragment(waterParkFragment,"WaterPark");
// adapter.addFragment(dryParkFragment,"DryPark");
// adapter.addFragment(facilitiesFragment.newInstance(),"Facilities");
adapter.addFragment(WaterParkFragment.newInstance(),"WaterPark");
adapter.addFragment(DryParkFragment.newInstance(),"DryPark");
adapter.addFragment(FacilitiesFragment.newInstance(),"Facilities");
viewPager.setAdapter(adapter);
}
}
DryParkFragment (Same with WaterParkFragment & FacilitiesFragment):
package com.ardityo.android.transeraapps.ui.home.tabs.drypark;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.settings.SettingsViewModel;
public class DryParkFragment extends Fragment {
public DryParkFragment() {
// Required empty public constructor
}
public static DryParkFragment newInstance() {
Bundle args = new Bundle();
DryParkFragment fragment = new DryParkFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.content_home_2, container, false);
}
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_calls_fragment, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
}
content_home_2.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.tabs.drypark.DryParkFragment"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mascot_head" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test" />
</LinearLayout>
The problem comes from using ViewPager inside NestedScrollView . This may also happen when you use CoordinatorLayout . You have two options to achieve that .
1 . ViewPager2 :
The first option is to use ViewPager2 . Just take a look :
https://developer.android.com/jetpack/androidx/releases/viewpager2
2 . Use custom ViewPager :
Here is a class for you that can determine its height based on childs.
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int biggestHeightMeasureSpec = 0;
for(int i = 0 ; i < getChildCount() ; i++)
{
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
if(heightMeasureSpec > biggestHeightMeasureSpec)
biggestHeightMeasureSpec = heightMeasureSpec;
}
}
super.onMeasure(widthMeasureSpec, biggestHeightMeasureSpec);
}
}
Finally just use it in your XML layout :
<PATH.TO.YOUR.CustomViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Try using viewpager 2, dont forget to use newest library
-> https://developer.android.com/jetpack/androidx/releases/viewpager2?hl=id
The fragment shows up by default but I wanted it to be hidden/invisible until I click this button. The problem that I am experiencing is that when I click this button, the fragment won't show up. I'm a complete beginner when it comes to fragments.
My codes in my Main Activity:
package com.example.julian.tutorial_fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements TopSectionFragment.TopSectionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View frag = findViewById(R.id.fragment3);
frag.setVisibility(View.GONE);
}
//This gets called by the TopFragment when the user clicks the button
#Override
public void createMeme(String top, String bottom) {
BottomPictureFragment bottomFragment = (BottomPictureFragment)getSupportFragmentManager().findFragmentById(R.id.fragment2);
bottomFragment.setMemeText(top, bottom);
}
//this is the onButtonClick
public void sample(View view) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment_Search hello = new Fragment_Search();
fragmentTransaction.add(R.id.fragment3, hello, "HELLO");
fragmentTransaction.commit();
}
}
My codes in Fragment_Search:
package com.example.julian.tutorial_fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Julian on 8/17/2017.
*/
public class Fragment_Search extends Fragment {
public interface Fragment_SearchInterface {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sample_layout, container, false);
return view;
}
}
My activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.julian.tutorial_fragment.MainActivity">
<RelativeLayout
android:layout_width="377dp"
android:layout_height="498dp"
tools:layout_editor_absoluteY="8dp"
tools:layout_editor_absoluteX="8dp">
<fragment
android:id="#+id/fragment2"
android:name="com.example.julian.tutorial_fragment.BottomPictureFragment"
android:layout_width="250dp"
android:layout_height="250dp"
tools:layout="#layout/bottom_picture_fragment"
tools:layout_editor_absoluteX="67dp"
tools:layout_editor_absoluteY="223dp"
android:layout_marginBottom="30dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<fragment
android:id="#+id/fragment"
android:name="com.example.julian.tutorial_fragment.TopSectionFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/top_section_fragment"
tools:layout_editor_absoluteX="42dp"
tools:layout_editor_absoluteY="16dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/fragment2"
android:layout_alignStart="#+id/fragment"
android:text="Button"
android:onClick="sample"/>
<fragment
android:id="#+id/fragment3"
android:name="com.example.julian.tutorial_fragment.Fragment_Search"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_below="#+id/button2"
android:layout_marginTop="92dp"
android:layout_toStartOf="#+id/button2" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
change your sample function and add this
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.your_layout, new Fragment_Search())
.addToBackStack(null)
.commit();
am creating android application which will displays youtube videos on horizontal(Landscape) list view similar to application in screen-shot. And when i click on one of the video then it should play, which is what currently happening, am able to load all the youtube videos along with there thumbnails in simple list view(Vertical) in android, but i couldn't found out a way so far, using which I can show all videos in the youtube playlist in the manner as shown in the following screen shot layout view.
If any one knows how I could show my video list in horizontal(Landscape) layout as depicted in the attached screen-shot, it would be great help for me.
Please visit link to see the screenshot: https://sc-cdn.scaleengine.net/i/954e89ab4d5fef83bb19009107d71c60.png
Thank You.
Here Sample code
Sorry for the Logs, as am running it on device.
MainActivity
package in.wptrafficanalyzer.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager pager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating FragmentPagerAdapter */
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
pager.setAdapter(pagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyFragment.java
package in.wptrafficanalyzer.viewpagerdemo;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment extends Fragment implements YouTubePlayer.OnInitializedListener{
int mCurrentPage;
public static final String API_KEY = "AIzaSyBaoObw6vr4uCJnCXXXXXXXX";
//http://youtu.be/<VIDEO_ID>
public static final String VIDEO_ID = "dKLftgvYsVU";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = data.getInt("current_page", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.myfragment_layout, container,false);
YouTubePlayerView tv = (YouTubePlayerView ) v.findViewById(R.id.youtube_player);
tv.initialize(API_KEY, this);
return v;
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
//Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
}
MyFragmentPagerAdapter.java
package in.wptrafficanalyzer.viewpagerdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 5;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);
return myFragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page #" + ( position + 1 );
}
}
activity_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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
myfragment_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="vertical" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp"
/>
</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.viewpagerdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="17" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter
android:label="#string/app_name"
>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
You are doing it wrong. Your my Fragment Xml should look like this:
<?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="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp"
/>
</android.support.v4.view.ViewPager>
</LinearLayout>
Now code accordingly and Post your logcat for crash issue resolution.
I created a Tabbed Activaity using Android Studio 1.2.2 wizard, I hope to close this window when I click the button btnClose, I write the code rootView.getContext().finish(); , but it's wrong,
and PlaceholderFragmentOld.this.finish(); is wrong too.
How can I do? Thanks!
PlaceholderFragmentOld.java
package ui.tab;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.Button;
import com.google.android.gms.ads.AdView;
import info.dodata.messagecleanup.R;
import bll.PublicParFun;
import info.dodata.messagecleanup.R;
public class PlaceholderFragmentOld extends Fragment {
private AdView adView;
public PlaceholderFragmentOld() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleanup_delete_fragment_old, container, false);
adView=(AdView) rootView.findViewById(R.id.adView);
PublicParFun.SetAD(adView);
SetButtons(rootView);
return rootView;
}
private void SetButtons(final View rootView){
rootView.findViewById(R.id.btnClose).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootView.getContext().finish();
}
});
}
}
CleanupDelete.java
package ui;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.dodata.messagecleanup.R;
import ui.tab.PlaceholderFragmentOld;
import ui.tab.PlaceholderFragmentPerson;
import ui.tab.PlaceholderFragmentReduce;
import ui.tab.PlaceholderFragmentTrim;
public class CleanupDelete extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cleanup_delete);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new PlaceholderFragmentOld();
break;
case 1:
fragment = new PlaceholderFragmentReduce();
break;
case 2:
fragment = new PlaceholderFragmentTrim();
break;
case 3:
fragment = new PlaceholderFragmentPerson();
break;
default:
throw new IllegalArgumentException("Invalid section number");
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.Tab_Old);
case 1:
return getString(R.string.Tab_Reduce);
case 2:
return getString(R.string.Tab_Trim);
case 3:
return getString(R.string.Tab_Person);
}
return null;
}
}
}
cleanup_delete.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
/>
cleanup_delete_fragment_old.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/border_ui" >
<LinearLayout
android:id="#+id/linearLayoutMain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingTop="20dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:orientation="vertical" >
<TextView
android:id="#+id/tVDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
style="#style/myTextDesciption"
android:text="This is a descript"/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutToolBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:weightSum="4" >
<Button
android:id="#+id/btnDelete"
style="#style/myTextMedium"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:text="#string/BtnDelete" />
<Button
android:id="#+id/btnClose"
style="#style/myTextMedium"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:text="#string/BtnClose" />
</LinearLayout>
</RelativeLayout>
finish() can only be called in an Activity. Given that, you do it this way:
// Somewhere in your fragment
private void finishActivity() {
if(getActivity() != null) {
getActivity().finish();
}
}
And you could then call that method to finish your Activity:
// Somewhere in your click listener
finishActivity();
IMPORTANT: There is a possibility for getActivity() to return null. This is especially dangerous when the fragment is being detached from your Activity (when using a ViewPager or when you're juggling between numerous fragments in an activity). Calling it without checking will pose your code to the threat of NullPointerException.
You may do something like this.
#Override
public void onClick(View v) {
getActivity().finish();
}
You should use getActivity().finish();
In order to move from a fragment to activity using Kotlin, add the code below:
if(activity != null) {
activity?.finish()
}
I'm trying to learn fragments on android and my code is not working.
FragmentCustomAnimations contains MainActivity.
What i want is the frame MainActivity to change when i push the button on MainActivity.
The error message on logcat is Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.FragmentCustomAnimations for onClick handler on view class android.widget.Button with id 'button1'
Eventhough there is no function sendmessage in all my file.
FYI, its working when i put the button on FragmentCustomAnimations.
Is it impossible to use the button on fragment to trigger action to change the fragment itself?
Here is the code:
FragmentCustomAnimations.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentCustomAnimations extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_stack);
if (savedInstanceState == null) {
Fragment newFragment = InitialFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public static class InitialFragment extends Fragment {
static InitialFragment newInstance() {
InitialFragment f = new InitialFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
return v;
}
}
}
fragment_stack.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:background="#drawable/window2x"
android:layout_width="match_parent" android:layout_height="match_parent">
<FrameLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
MainActivity.java
package com.example.myfirstapp;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button inner = (Button) findViewById(R.id.button1);
inner.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
getActionBar().setDisplayShowHomeEnabled(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
addFragmentToStack();
}
void addFragmentToStack() {
Fragment newFragment = CountingFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
R.animator.fragment_slide_left_exit,
R.animator.fragment_slide_right_enter,
R.animator.fragment_slide_right_exit);
ft.replace(R.id.simple_fragment, newFragment);
ft.addToBackStack(null);
ft.commit();
}
public static class CountingFragment extends Fragment {
static CountingFragment newInstance() {
CountingFragment f = new CountingFragment();
Bundle args = new Bundle();
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_display_message, container, false);
return v;
}
}
}
activity_main.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="?android:attr/actionBarSize"
android:layout_gravity="center_vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edit_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_message"
android:layout_gravity="center_vertical"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextEmail"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/editTextPassword"
android:inputType="textPassword" />
<Button
android:id="#+id/button1"
style="#style/CodeFont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#drawable/custom_button"
android:text="#string/button_send" />
</LinearLayout>