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.
Related
I'm trying to learn android and am having an issue with this project. I have set up a fragment tab host with four fragments. What I would like to do is have the first three fragments be interactive with the user and when they tab over to the 4th tab, it will display all the information they put in on the first three. I figured I can pass the info overriding on onPause() as the trigger as I don't want to use a button press. Right now, I'm just trying to get the EditText to work to make sure I'm doing everything right. I'm not sure if I'm using the fragment transaction correctly, or the way I'm trying to collect the edit text field. Later on I hope to pass the information via a bundle. Any help would be appreciated.
Main:
package valdes.fragmenttabsmenu;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements WelcomeFragment.WelcomeListener {
private FragmentTabHost mTabHost;
private String firstName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Home").setIndicator("Home", null), WelcomeFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Demographics").setIndicator("Demographics", null), DemographicsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Questions").setIndicator("Questions", null), QuestionsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Overview").setIndicator("Overview", null), OverviewFragment.class, null);
}
#Override
public void getFristName(String first_Name){
firstName = first_Name;
OverviewFragment fragment = new OverviewFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setFirstName(firstName);
ft.addToBackStack(null);
ft.commit();
}
}
Fragment 1 - getting info
package valdes.fragmenttabsmenu;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class WelcomeFragment extends Fragment {
public WelcomeFragment() {
// Required empty public constructor
}
interface WelcomeListener{
public void getFristName(String firstName);
}
private WelcomeListener listener;
private String firstName;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
EditText editText = (EditText) view.findViewById(R.id.first_name);
firstName = editText.getText().toString();
return view;
}
#Override
public void onAttach(Context context){
super.onAttach(context);
this.listener = (WelcomeListener)context;
}
#Override
public void onPause(){
super.onPause();
if(listener != null){
listener.getFristName(firstName);
}
}
}
Fragment 1 XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:text="#string/welcome_message"/>
<EditText
android:id="#+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/first_name"/>
<EditText
android:id="#+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/last_name"/>
<Spinner
android:id="#+id/birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/months"/>
</LinearLayout>
Fragment 2 - getting info
package valdes.fragmenttabsmenu;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
private String firstName;
private String lastName;
public OverviewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_overview, container, false);
}
#Override
public void onStart(){
super.onStart();
View view = getView();
if(view != null){
TextView name = (TextView) view.findViewById(R.id.OV_name);
name.setText(firstName);
}
}
public void setFirstName(String firstName){this.firstName = firstName;}
}
Fragment 2 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"
tools:context="valdes.fragmenttabsmenu.OverviewFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:layout_weight="1"
android:text="#string/overview"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textSize="40sp"
android:text="Responses go here"/>
<TextView
android:id="#+id/OV_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="TEST"/>
<Button
android:id="#+id/submit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/submit"/>
</LinearLayout>
Create a Listner for get/set data between fragments and implement it on activity like this
InteractionLister.java
public interface InteractionLister {
void setData(String data);
String getData();
}
MainActivity.java
public class TabActivity extends Activity implements InteractionLister{
private String mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setData(String data) {
this.mData = data;
}
#Override
public String getData() {
return mData;
}
}
TabFragment1.java
public class TabFragment1 extends Fragment {
InteractionLister interactionLister;
private static final String TAG = TabFragment1.class.getSimpleName();
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.w(TAG,"Data from other fragment " + interactionLister.getData());
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
interactionLister = (InteractionLister) activity;
}
}
In portrait, it gives null point exceptioin when the list item is clicked but landscape works just fine... In AnotherAcitivity.java Fragment f2 gets null while debugged...
package com.example.myfragmentqadvancedel;
import com.example.myfragmentqadvancedel.FragmentA.Communicator;
import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
public class MainActivity extends Activity implements Communicator{
FragmentA f1;
FragmentB f2;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
f1=(FragmentA) manager.findFragmentById(R.id.fragment1);
f1.setCommunicator(this);
}
#Override
public void respond(int index) {
f2=(FragmentB) manager.findFragmentById(R.id.fragment2);
if (f2!=null && f2.isVisible()) {
f2.changeData(index );
}else {
Intent intent = new Intent(this,AnotherActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
FragmentA
package com.example.myfragmentqadvancedel;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator communicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_a, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
list=(ListView) getActivity().findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.chapters, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
public void setCommunicator(Communicator communicator) {
this.communicator = communicator;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
communicator.respond(i);
}
public interface Communicator{
public void respond(int index);
}
}
AnotherActivity.java
package com.example.myfragmentqadvancedel;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
public class AnotherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Intent intent = getIntent();
int index=intent.getIntExtra("index", 0);
FragmentB f2= (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
if(f2!=null) <-- f2 gets null, index gets +ve value as checked in debugger
f2.changeData(index);
}
}
FragmentB
package com.example.myfragmentqadvancedel;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment{
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
text=(TextView) getActivity().findViewById(R.id.textView1);
}
public void changeData(int index){
String[] descriptions = getResources().getStringArray(R.array.description);
text.setText(descriptions[index]);
}
}
logcat
05-27 16:40:37.866: E/AndroidRuntime(961): FATAL EXCEPTION: main
05-27 16:40:37.866: E/AndroidRuntime(961): java.lang.NullPointerException
05-27 16:40:37.866: E/AndroidRuntime(961): at com.example.myfragmentqadvance.MainActivity.respond(MainActivity.java:26)
05-27 16:40:37.866: E/AndroidRuntime(961): at com.example.myfragmentqadvance.Fragment1.onItemClick(Fragment1.java:42)
05-27 16:40:37.866: E/AndroidRuntime(961): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-27 16:40:37.866: E/AndroidRuntime(961): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
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: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=".MainActivity">
<fragment
android:id="#+id/fragment1"
android:name="com.example.myfragmentqadvancedel.FragmentA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#0f0">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00f" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#fff"/>
</LinearLayout>
activity_another.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: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=".AnotherActivity" >
<fragment
android:id="#+id/fragment2"
android:name="com.example.myfragmentqadvancedel.FragmentB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp" />
</RelativeLayout>
Your interface in Fragment A seems to be Null. Instead of setting the Interface after finding fragment by id, you should use onAttach(Activity activity) method. Here you can force your parent Activity to implement this interface. Check out the code below.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
/* Check if the Activity implemented Callbacks from this Fragment */
try {
communicator = (Communicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement " + this.getClass().getSimpleName() + "Callbacks");
}
}
when i keep the code frm onCreate to onStart of AnotherActivity , it works... dont know whats the prob to put them in onCreate
public class AnotherActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
int index=intent.getIntExtra("index", 0);
FragmentB f2= (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
if(f2!=null)
f2.changeData(index);
}
}
I have created a fragment activity with 3 tabs. When I move from tab 1 to tab 3, it takes around 5 seconds to load tab 3( due to some time consuming task ). During this loading time, I want to show a dialog.
I put the dialog inside onTabSelected(), but the dialog shows up only after the 3rd tab display comes up. I want it to show between "the time I clicked the 3rd tab" and "the time the 3rd tab actually comes up". Please do let me know ur suggestions.
Editted :
Sample code :
MainActivity.java:
package com.example.trial;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private static final String STATE_SELECTED_NAVIGATION_ITEM ="selected_navigation_item";
ProgressDialog nDialog;
Fragment dashboardFrag = new DashboardTab();
Fragment Tab1 = new Tab1();
Fragment Tab2 = new Tab2();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText("Tab1")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab2")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Tab3")
.setTabListener(this));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
if (tab.getPosition() == 0) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Tab1).commit();
}
else if (tab.getPosition() == 1) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Tab2).commit();
}
else if (tab.getPosition() == 2) {
showProgress1();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, dashboardFrag).commit();
}
}
void showProgress1(){
nDialog = new ProgressDialog(MainActivity.this); //Here I get an error: The constructor ProgressDialog(PFragment) is undefined
nDialog.setMessage("Loading..");
nDialog.setTitle("Fetching Data");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
}
Tab1.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
return rootView;
}
}
Tab2.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Tab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);
return rootView;
}
}
DashboardTab.java
package com.example.trial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DashboardTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
}
activity_main.xml
<FrameLayout android:id="#+id/container" android:layout_height="match_parent" android:layout_width="match_parent" tools:context=".MainActivity" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
</FrameLayout>
tab1.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab1"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
tab2.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tab2"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
dashboard.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dashBoard"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I didn't find something like you are telling, may be you are having issues with your phone memory, however an approach to show dialog when performing time consuming tasks through your code
public class DashboardTab extends Fragment {
private ProgressDialog nDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dashboard, container, false);
showProgress1();
YourTimeConsumingTask();
nDialog.dismiss();
return rootView;
}
private void YourTimeConsumingTask(){
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void showProgress1() {
nDialog = new ProgressDialog(getActivity()); // Here I get an error:
// The constructor
// ProgressDialog(PFragment)
// is undefined
nDialog.setMessage("Loading..");
nDialog.setTitle("Fetching Data");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
}
I am getting error following error. give me a suggestion if you faced the same issue.
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MainActivity.java
Error:(9, 8) error: MainActivity is not abstract and does not override abstract method Message(String) in Communicator
fragmentslayout\app\src\main\java\com\example\fragmentslayout\app\MyListFragment.java
Error:(23, 28) error: incompatible types: OnItemSelectedListener cannot be converted to Communicator
My Code:
MainActivity.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity implements Communicator
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onRssItemSelected(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}
}
DetailFragment.java
package com.example.fragmentslayout.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
return view;
}
// we call this method when button from listfragment is clicked
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.display_tv);
view.setText(item);
}
}
MyListFragment.java
package com.example.fragmentslayout.app;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyListFragment extends Fragment implements OnClickListener
{
private Communicator communicator;
Button android_btn, ios_btn, windows_btn;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.Communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
// Initialize Views
android_btn = (Button) view.findViewById(R.id.android_btn_id);
ios_btn = (Button) view.findViewById(R.id.ios_btn_id);
windows_btn = (Button) view.findViewById(R.id.windows_btn_id);
// set on click Listeners for buttons
android_btn.setOnClickListener(this);
ios_btn.setOnClickListener(this);
windows_btn.setOnClickListener(this);
return view;
}
public interface OnItemSelectedListener {
public void Message(String OS_Name);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.android_btn_id:
updateFragment("Android");
break;
case R.id.ios_btn_id:
updateFragment("IOS");
break;
case R.id.windows_btn_id:
updateFragment("Windows");
break;
}
}
private void updateFragment(String OS_Name) {
communicator.Message(OS_Name);
}
}
Communicator Interface
package com.example.fragmentslayout.app;
public interface Communicator {
public void Message(String tutUri);
}
Layout:
activity_main.xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<fragment
android:id="#+id/list_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.example.fragmentslayout.app.MyListFragment" >
</fragment>
<fragment
android:id="#+id/detail_Fragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
class="com.example.fragmentslayout.app.DetailFragment" >
</fragment>
</LinearLayout>
detail_fragment.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:background="#FFFF99"
android:orientation="vertical"
android:padding="20dp" >
<TextView
android:id="#+id/display_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="40sp" />
</LinearLayout>
list_fragment.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:background="#CCFF99"
android:orientation="vertical"
android:padding="5dp" >
<Button
android:id="#+id/android_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<Button
android:id="#+id/ios_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IOS" />
<Button
android:id="#+id/windows_btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Windows" />
</LinearLayout>
Your MainActivity implements Communicator,so you must override abstract method Message(String). Just add the method Message(String) to your MainActivity.
Your MainActivity implements Communicator, is your Communicator in activity same Communicator in fragment!!,so you must override abstract method Message(String), move your code in onRssItemSelected(string) function to new message function
just add this function to mainactivity
#Override
public void Message(String OS_Name) {
DetailFragment detailfragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail_Fragment);
if (detailfragment != null && detailfragment.isInLayout()) {
detailfragment.setText(OS_Name);
}
}
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.