I have been trying to add a youtube player in a fragment.
had some overlay errors. tried different things and resolved them, now the error is quite awkward.
I don't know what is wrong here.
the error is YouTubePlayerView is obscured by com.google.android.youtube.player.YouTubePlayerView
complete error:
W/YouTubeAndroidPlayerAPI: YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is obscured by com.google.android.youtube.player.YouTubePlayerView{2db246cd V.E..... .......D 20,20-596,344}. YouTubePlayerView is completely covered, with the distance in px between each edge of the obscuring view and the YouTubePlayerView being: left: 0, top: 0, right: 0, bottom: 0..
MainActivity.java
package onestop.com.youtubefragmenttest;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public static final String API_KEY = "AIzaSyDlS41-LGiRTToI4GDDRHglf-VY1wCxvtc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YoutubeFragment fragment = new YoutubeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.fragment, fragment)
.addToBackStack(null)
.commit();
}
}
YouTubeFragment.java
package onestop.com.youtubefragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.OnInitializedListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class YoutubeFragment extends Fragment {
public static final String API_KEY = "AIzaSyDlS41-LGiRTToI4GDDRHglf-VY1wCxvtc";
public static final String VIDEO_ID = "lfG2-FFL6fY";
public YoutubeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_youtube, container, false);
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {
// YouTubeプレーヤーの初期化成功
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer yPlayer, boolean wasRestored) {
if (!wasRestored) {
yPlayer.cueVideo(VIDEO_ID);
}
}
// YouTubeプレーヤーの初期化失敗
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
// YouTube error
String errorMessage = error.toString();
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
});
return rootView ;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="onestop.com.youtubefragmenttest.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="300dp"
android:name="onestop.com.youtubefragmenttest.YoutubeFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
fragment_youtube.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:padding="10dp">
</FrameLayout>
In my case the problem was, that I was displaying the same video twice.
You may want to check if this is a device specific issue, based from this SO question this issue may be due to a transparent view is overlapping YouTubeAndroidPlayer view. Also check your code if there is any overlays when the player is playing.
YouTubePlayerFragment
Note that while videos are playing, this View has a minimum size of 200x110 dp. If you make the view any smaller, videos will automatically stop playing. Also, it is not permitted to overlay this fragment's view with other views while a video is playing.
YouTubePlayerView
This view does not support padding. To achieve the same effect, wrap the view in another ViewGroup or give it margins
Hope this helps!
Related
Inside a viewpager fragment is having a network call to load the data. Due to this network call it creates a lag for users. How can i handle network call inside a fragment which reside inside a viewpager. I just dont want my users to see the lag as it takes 4-7 seconds to load a fragment. what is efficent way to load a fragment via network call for Viewpager
below is code for Activity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.test.androidtest20202.R;
import com.test.androidtest20202.adapter.ViewPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerActivity extends AppCompatActivity {
ViewPagerAdapter adapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager);
viewPager = findViewById(R.id.viewpager);
ArrayList<Integer> task_ids = new ArrayList<>();
for(int i=0;i<5;i++){
task_ids.add(i);
}
adapter = new ViewPagerAdapter(this, getSupportFragmentManager(),task_ids);
viewPager.setAdapter(adapter);
}
}
Below activity xml layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".activity.ViewPagerActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#color/white"
android:largeHeap="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Below is my Viewpager Adapter :
import android.content.Context;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.test.androidtest20202.fragments.ViewPagerFragment;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<Integer> taskid;
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public ViewPagerAdapter(Context context, #NonNull FragmentManager fm, ArrayList<Integer> taskid) {
super(fm);
this.taskid = taskid;
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle bundle = new Bundle();
bundle.putInt("COMPLETED_TASKID", taskid.get(position));
fragment = new ViewPagerFragment();
registeredFragments.put(position, fragment);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public int getCount() {
return taskid.size();
}
}
Below is my Viewpager Fragment code:
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
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 com.test.androidtest20202.R;
import com.test.androidtest20202.pojo.SaleskenResponse;
import com.test.androidtest20202.util.RestApiClient;
import com.test.androidtest20202.util.RestUrlInterface;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ViewPagerFragment extends Fragment {
private static final String TAG = "ViewPagerFragment";
private ViewGroup container;
private LayoutInflater inflater;
#BindView(R.id.textView2)
TextView textView;
private AsyncTask mAsyncTask;
public RestUrlInterface restUrlInterface;
Integer taskid = -1;
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
this.container = container;
this.inflater = inflater;
return initializeView();
}
private View initializeView() {
final View view;
view = inflater.inflate(
R.layout.fragment_laout, container, false);
ButterKnife.bind(this, view);
restUrlInterface = RestApiClient.getClient(getContext()).create(RestUrlInterface.class);
if (getArguments() != null) {
taskid = getArguments().getInt("COMPLETED_TASKID");
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Call<SaleskenResponse> task_details = restUrlInterface.getTaskDetail(getString(R.string.token), taskid );
task_details.enqueue(new Callback<SaleskenResponse>() {
#Override
public void onResponse(Call<SaleskenResponse> call, Response<SaleskenResponse> response) {
switch (response.code()) {
case 200:
textView.setText( response.body().toString());
}
}
#Override
public void onFailure(Call<SaleskenResponse> call, Throwable t) {
}
});
}
}
Below is Fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
So as the data only need to be loaded once I would do this in the activity onCreate just after you have created your task_ids ArrayList.
You seem to be using a custom RestAPI package, but most package do Network request asynchronously, so when you get a response for each request you would then store them in a shared viewmodel using the unique task_id's as an index.
The shared viewmodel can then be observed from the fragment and when the data is available the fragment will be notified to use it.
So basically start the Network load as soon as the Activity starts, to give it a head start before the viewpager is setup and the first Fragment is loaded, and storing your data independently of the Activity and Fragments.
Note this won't guarantee that the first fragment in the viewpager will have it's data available by the time it is shown but at least it should be part way to having it available and by the time the user swaps to the second page in the viewpager that data should already be available.
How to share data between Fragments with a shared viewmodel example is at https://blog.mindorks.com/shared-viewmodel-in-android-shared-between-fragments (this example is between 2 fragments but the same concept can be used for comms between the background RestAPI calls in the Activity and each Fragment in the viewpager.
There might be a trade off on first page load time between requesting the data for all task_id's in parallel vs doing them sequentially start with the first page and then once that has loaded request the next one, etc.
Sorry no code example (other than in the link on how to use shared viewmodel) but is more of an architectural answer as you seem to be using a custom RestAPI package I'm not familiar with.
This is basically caching the data for each fragment as soon as the activity starts and the Fragments just display the cached data.
If you can cache between each time the Activity is started you could instead of the shared viewmodel use a Database like Android Rooms, then when it Activity is started it has the data from last time the Activity was started and really it could in the background just check the freshness of the data stored in the database with a RestAPI request.
I am new to android and cannot find a solution online. I have a navigation drawer that leads to the fragment 'RecentNews', which is related to it's XML 'fragment_recent_news'. I have a WebView (webview) setup in the XML, and have set up the fragment so that it should load a page, but it does not. What am I doing incorrectly? I am unsure if the way to properly do this has changed in the past year because nothing online has worked. Thanks
fragment_recent_news(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="com.hardingsoftware.hrcfitness.RecentNews">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webview"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
RecentNews:
package com.hardingsoftware.hrcfitness;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class RecentNews extends Fragment {
WebView webView;
public RecentNews() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recent_news, container, false);
WebView myWebView = (WebView) rootView.findViewById(R.id.webview);
myWebView.loadUrl("www.hrcfitness.com/recent-news/");
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
EDIT: I have the page loading now, however I now have another issue, where the webview seems to ignore the relative layout and part of it is lying under the main bar.
I'm trying to add a Fragment to my FrameLayout, it seems that it is added correctly, but then i can't see the text of the TextView.
Fragment Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text1"
android:text="Hello"
android:background="#34f5d6"/>
</LinearLayout>
The FragmentClass:
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.CharacterPickerDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class TimerClass extends Fragment {
public static Fragment newInstance(Context context) {
TimerClass fragment = new TimerClass();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
ViewGroup root=(ViewGroup)inflater.inflate(R.layout.mylayout,container,false);
return root;
}
}
And the code i use to add the fragment to the FrameLayout
FragmentTransaction tx= getFragmentManager().beginTransaction();
Fragment fragment= TimerClass.newInstance(getApplicationContext());
tx.replace(R.id.fl, fragment);
tx.commit();
I don't undestand why it doesn't show the text, I tryed to change the color of the text but it doesn't work.
If I change the background of the TextView, it works; also if I add an OnClockListener on the TextView, it works. Only it doesn't show the text.
Can you help me?
EDIT:
I found the solution: the problem was with the FrameLayout; it's top part was covered by the action bar.
By fixing the layout of the FrameLayout the problem disappeared.
First simply change this
ViewGroup root=(ViewGroup)inflater.inflate(R.layout.mylayout,container,false);
return root;
to
View root = inflater.inflate(R.layout.mylayout,container,false);
return root;
Also this one
public static Fragment newInstance(Context context) {
TimerClass fragment = new TimerClass();
return fragment;
}
to
public static TimerClass getInstance() {
TimerClass fragment = new TimerClass();
return fragment;
}
I think issue is only with height and width of your TextView because you have sated them as match_parent
so try to replace
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text1"
android:text="Hello"
android:background="#34f5d6"/>
with
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text1"
android:text="Hello"
android:background="#34f5d6"/>
This is my first time working with the WebView widget and I've done searching via Google and on StackExchange and cannot find a solution to my problem.
I have placed a WebView on a FragmentActivity, loaded by a main Activity, and it is just blank no matter if I use "http://www.google.com" as a URL or if I specify a local .html file (very simple one containing a couple paragraphs, header, and link). It is not shown below, but my AndroidManifest.xml has the INTERNET permission (and EXTERNAL_STORAGE).
activity_main.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:name="com.adamtcarlson.websiteviewer.MainActivityFragment"
tools:context=".MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<FrameLayout
android:id="#+id/frm_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.java:
import android.net.Uri;
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.FragmentTransaction;
import android.util.Log;
public class MainActivity extends FragmentActivity {
/**
* The Activity's tag.
*/
private static final String Tag = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(Tag, "onCreate()");
populateContentFragment(false);
}
private void populateContentFragment(boolean addToBackStack) {
Log.v(Tag, "populateContentFragment()");
Uri uri = Uri.parse("http://www.google.com/");
//Uri uri = Uri.parse("file:///data/app/testpage.html");
Fragment fragment = WebBrowserFragment.newInstance(uri);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
.replace(R.id.frm_content, fragment);
if (addToBackStack) {
fragmentTransaction.addToBackStack(Tag);
}
fragmentTransaction.commit();
}
}
fragment_webbrowser.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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"
android:background="#AAAAAA">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/wbvBrowser">
</WebView>
</RelativeLayout>
WebBrowserFragment.java:
import android.annotation.SuppressLint;
import android.net.Uri;
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.webkit.WebView;
import android.webkit.WebViewClient;
/**
* A placeholder fragment containing a simple view.
*/
public class WebBrowserFragment extends Fragment {
private WebView wbvBrowser = null;
private String browserUri = null;
/**
* The Activity's tag.
*/
private static final String Tag = "WebBrowserFragment";
public WebBrowserFragment() {
Bundle args = getArguments();
if (args != null) {
browserUri = args.getString("Uri");
}
}
public static WebBrowserFragment newInstance(Uri uri) {
Log.v(Tag, "newInstance(). Uri: " + uri.toString());
WebBrowserFragment fragment;
if (uri != null) {
fragment = new WebBrowserFragment();
Bundle args = new Bundle();
args.putString("Uri", uri.toString());
fragment.setArguments(args);
}
else {
fragment = new WebBrowserFragment();
}
return fragment;
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(Tag, "onCreateView()");
View rootView = inflater.inflate(R.layout.fragment_webbrowser, container, false);
wbvBrowser = (WebView) rootView.findViewById(R.id.wbvBrowser);
wbvBrowser.getSettings().setJavaScriptEnabled(true);
wbvBrowser.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
wbvBrowser.loadUrl(browserUri);
return rootView;
}
}
I should note in the Fragment that I tried commenting out the .setWebViewClient() call but that also did nothing. I got the original code from a book I have, "Android Programming: The Big Nerd Ranch Guide." I can't see any errors or anything that looks out-of-place on the logcat log. I've tried viewing the app via the emulator, using API 10 and 19. I've also tried installing the .apk on my LG Ultimate 2 and all show a blank screen (I changed the background to the Fragment's RelativeLayout to gray to ensure the WebView was showing up).
Much thanks for any assistance.
wbvBrowser.loadUrl(browserUri);
browserUri is not set
simply add browserUri = getArguments().getString("Uri"); before the line.
i.e.
browserUri = getArguments().getString("Uri");
wbvBrowser.loadUrl(browserUri);
please help
When I run my ListFragment actitivy and click on a fragment (either Buick or Mazda), the layout of the fragment I clicked on is supposed to replace and cover the entire screen but the
container containing the list of cars stays on the screen and my fragment layout is shown below it. How can I make my fragment's layout replace the entire screen?
I couldn't post my AVD image showing the screen because I don't have enough reputatons to do
but the screen was showing as below when I clicked on the first item on the list.
Buick
Mazda
Hello! It's a Buick
my Mainactivity
package in.cars.demo;
import android.app.Activity;
import android.os.Bundle;
public class CarsMainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
My ListFragment activity
package in.cars.demo;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class CarsList extends ListFragment {
String[] cars = new String[] { "Buick", "Mazda" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListAdapter myListAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cars);
setListAdapter(myListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.cars_container, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
switch (position) {
case 0:
Fragment fragment1 = new Fragment1();
FragmentTransaction transaction1 = getFragmentManager().beginTransaction();
transaction1.replace(R.id.car_fragment, fragment1);
transaction1.addToBackStack(null);
transaction1.commit();
break;
case 1:
Fragment fragment2 = new Fragment2();
FragmentTransaction transaction2 = getFragmentManager().beginTransaction();
transaction2.replace(R.id.car_fragment, fragment2);
transaction2.addToBackStack(null);
transaction2.commit();
break;
}
}
}
Fragment1
package in.cars.demo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
}
Fragment2
package in.cars.demo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/car_fragment"
android:name="in.cars.demo.CarsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
cars_container.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:paddingLeft="4dp"
android:paddingRight="4dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"/>
</LinearLayout>
fragment1.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" >
<TextView
android:id="#+id/frag1TV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello! It's a Buick" />
</LinearLayout>
fragment2.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" >
<TextView
android:id="#+id/frag2TV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello! It's a Mazda" />
</LinearLayout>
The problem is that you set the layout_height of your fragment to wrap_content in your main.xml. The visible size will be reduced to the actual size of the fragment.
Change it to match_parent to fill the whole screen:
...
<fragment
android:id="#+id/car_fragment"
android:name="in.cars.demo.CarsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
...
Furthermore use match_parent instead of fill_parent in apps with API Level 8+. See this question for more information.
Edit:
You have to change the container for the Fragments. The Fragment set with the tag will be static. Every fragment will be set in addition to this container. To have a dynamic approach use a FrameLayout. Now you can replace the fragment which was in there before.
...
<FrameLayout
android:id="#+id/car_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
...
To show your CarsList you have to do a Fragment transaction in your Activity.
getFragmentManager() / getSupportFragmentManager()
.beginTransaction()
.replace(R.id.car_fragment, new CarsList())
.addToBackstack(null)
.commit();
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:clickable="true"
android:orientation="vertical">
Try to setUp a color background to your fragment. In this way the background covers the entire space.
It is a little bit late, but maybe I will help someone else. The problem is with 'fragment' in your activity xml layout file (main.xml). You have to change:
<fragment
android:id="#+id/car_fragment"
android:name="in.cars.demo.CarsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
to
<fragment
android:id="#+id/car_fragment"
android:name="in.cars.demo.CarsList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>