Just started learning android. Help please. I have three fragments, each has a button that must run one of the streams of the media player. How can I find the button of my activity in the fragment that would later attach to it a specific stream?
Tried to make a reference to the button so that:
btnStart = (Button) titleAdapter.frags[0].getView().findViewById(R.id.btnStart);
Did not work, an error java.lang.NullPointerException, what I'm doing wrong
public class TitleAdapter extends FragmentPagerAdapter {
private final String titles[] = new String[] { "FragA", "FragB", "FragC" };
private final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
code MainActivity.java:
public class MainActivity extends FragmentActivity {
final static String LOG_TAG = "myLogs";
static MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
static Button btnNews;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
pdaStream = (CheckBox) findViewById(R.id.pdaStream);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
initBar(music, AudioManager.STREAM_MUSIC);
}
#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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.news:
Intent intent = new Intent(this, RSSActivity.class);
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public static void initBar(SeekBar bar, final int stream) {
bar.setMax(am.getStreamMaxVolume(stream));
bar.setProgress(am.getStreamVolume(stream));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
am.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
}
public void onStartTrackingTouch(SeekBar bar) {
// no-op
}
public void onStopTrackingTouch(SeekBar bar) {
// no-op
}
});
}
}
code fragments similar, here's one of them
code FragmentA.java:
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
private static ProgressBar progressBar;
static CheckBox pdaStream;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
final Button Play = (Button) rootView.findViewById(R.id.btnStart);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
pdaStream = (CheckBox) getActivity().findViewById(R.id.pdaStream);
return rootView;
} }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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"
android:background="#drawable/background"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#drawable/bg_pager"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:thumb="#drawable/seek" />
<CheckBox
android:id="#+id/pdaStream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="70dp"
android:text="#string/chkbox" />
</RelativeLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStart"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="16sp"
android:onClick="onClick"
android:background="#drawable/play_button"/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
You can access like this, for example you want access to button of fragment frags[1]:
Button btnFragment = frags[1].getView().findViewById(R.id.yourButtonID);
hope it helps!
You have to pass a reference from your Activity to the Fragments. As you are creating the Fragments from your PagerAdapter, it has to have the reference as well. You can do this either in the constructor (new Fragment(Activity a)) or by a public variable Activity that you initalize from the activity after creating the PagerAdapter.
in the Activity:
x = new TitleAdapter();
x.mActivity = this; (while mActivity must be declared public in the TitleAdapter()
in the Adapter:
frags[0] = new FragmentA();
frags[0].mActivity = this.mActivity;
Then in your Fragment you can add a OnClickListener to your button.
Related
I am currently doing this android tutorial https://www.androidhive.info/2016/05/android-build-intro-slider-app/ .
I want to implement the onClick() event inside the viewpager page like if I clicked the text, it will direct me to another page.
Is it possible? If possible, please help me? Thanks
here is my code for viewPager.
public class welcomeActivity extends AppCompatActivity {
ViewPager viewPager;
private LinearLayout myLinear;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private MyViewPagerAdapter myViewPagerAdapter;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().
setSystemUiVisibility
(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
myLinear = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide1, R.layout.slide2, R.layout.slide3, R.layout.slide4, R.layout.slide5
};
addBottomDots(0);
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int current = getItem(+1);
if (current < layouts.length){
viewPager.setCurrentItem(current);
}else launchHomeScreen();
}
});
}
ViewPager.OnPageChangeListener viewPagerListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
addBottomDots(position);
if (position == layouts.length -1){
btnSkip.setVisibility(View.GONE);
btnNext.setText("Get Started..");
}
else {
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
myLinear.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
myLinear.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
//prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(welcomeActivity.this, MainActivity.class));
finish();
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public class MyViewPagerAdapter extends PagerAdapter{
private LayoutInflater inflater;
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(layouts[position],container,false);
container.addView(v);
return v;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
Here is my layouts. (activity_welcome.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_welcome">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="#dimen/dots_height"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#id/layoutDots"
android:background="#android:color/white" />
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#null"
android:text="Next"
android:textColor="#android:color/white" />
<Button
android:id="#+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#null"
android:text="BACK"
android:textColor="#android:color/white" />
</RelativeLayout>
slide1.xml
<?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/bg_screen1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_food" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_1_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:id="#+id/tvFood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_1_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
slide2.xml
<?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/bg_screen2">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_movie" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_2_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_2_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
After this line in your adapter :
View v = inflater.inflate(layouts[position],container,false);
Add:
TextView tv =(TextView) v.findViewById(R.id.yourTextView);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do your stuff here whatever you want to do upon click
}});
public class IntroFragment_1 extends Fragment {
private String title;
private int page;
ImageView intro_images_1;
Animation xmlAnimationSample;
// newInstance constructor for creating fragment with arguments
public static IntroFragment_1 newInstance(int page, String title) {
IntroFragment_1 fragmentFirst = new IntroFragment_1();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro_view_1, container, false);
intro_images_1 = view.findViewById(R.id.intro_images_1);
xmlAnimationSample = AnimationUtils.loadAnimation(getContext(),R.anim.zoom_intro);
intro_images_1.startAnimation(xmlAnimationSample);
return view;
}
}
MyViewPagerAdapter
public static class MyViewPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return IntroFragment_1.newInstance(0, "Page # 1");
case 1: // Fragment # 0 - This will show FirstFragment different title
return IntroFragment_1.newInstance(0, "Page # 1");
case 2: // Fragment # 1 - This will show SecondFragment
return IntroFragment_1.newInstance(0, "Page # 1");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
layouts = new int[]{0, 1, 2,};
I'm encountering slow/laggy behaviour when swithcing between frgaments using a drawerlayout. I've read up here on stackoverflow and elsewhere regarding solving this issue and a major piece of advice e.g. as seen here is to populating bits of fragment related views elsewhere hence my question of how best can one do the populating part outside of onCreateView() to avoid the laggy behaviour.
Any help is appreciated.
My code is as follows:
My main activity below:
/*! Main activity class */
public class MainActivity extends ActionBarActivity implements FragListener {
/** Private vars */
private DrawerLayout drawerLayout;
private ListView lvDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private CharSequence drawerTitle;
private CharSequence title;
private DrawerLayoutAdapter drawerLayoutAdapter;
private List<DrawerLayoutDrawer> lvDrawerLayoutData;
/** Public vars */
public static String TAG = "MainActivity";
public MainActivity mainActivity;
public Display display;
public Typeface officialBoldFont, officialRegularFont;
public TextView actionBarTView, tvActionBarTitle = null;
public Fragment fragment;
//!<
public MainActivity() {
}
//!<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getTitle() is part of Activity
title = drawerTitle = getTitle();
// Obtain the normal device display area
display = getWindowManager().getDefaultDisplay();
// Set official font
officialRegularFont = Typeface.createFromAsset(this.getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(this.getAssets(), "square721extendedbold.ttf");
// Show action bar
getSupportActionBar().show();
// Inflate the custom action bar
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mCustomActionView = inflator.inflate(R.layout.actionbar_layout, null);
tvActionBarTitle = (TextView) mCustomActionView.findViewById(R.id.tv_action_bar_title);
tvActionBarTitle.setTypeface(officialBoldFont);
tvActionBarTitle.setTextColor(Color.parseColor("#000000"));
tvActionBarTitle.setTextSize(14.5f);
getSupportActionBar().setCustomView(mCustomActionView);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffFFCC00));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
// Inflate and customise the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerShadow(new ColorDrawable(0xffFF0000), GravityCompat.START);
drawerLayout.setBackgroundResource(R.drawable.bgnd_drawerlayout_default);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
// Inflate and customise the drawer layout list and drawer layout adapter
lvDrawerLayout = (ListView) findViewById(R.id.lv_drawer);
lvDrawerLayout.setDividerHeight(2);
// Below is the listview's bgnd and is different from bgnd_lv_item_drawerlayout.xml which is the bgnd for the items in this LV
lvDrawerLayout.setBackgroundResource(R.drawable.bgnd_lv_drawerlayout_default);
lvDrawerLayoutData = new ArrayList<DrawerLayoutDrawer>();
lvDrawerLayoutData.add(new DrawerLayoutDrawer("ADMINISTRATION", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("FINANCE CALCULATOR", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("EXIT", R.drawable.ic_test));
drawerLayoutAdapter = new DrawerLayoutAdapter(this, R.layout.lv_layout_drawer, lvDrawerLayoutData, officialRegularFont, officialBoldFont);
lvDrawerLayout.setAdapter(drawerLayoutAdapter);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Call starting fragment
if (savedInstanceState == null) {
callStartingFrag(0);
}
}
//!< Call starting fragment
public void callStartingFrag(int position) {
Bundle args = new Bundle();
fragment = new FragmentOne();
args.putString(" ", lvDrawerLayoutData.get(position).getItemName());
args.putInt(" ", lvDrawerLayoutData.get(position).getImgResID());
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
//!< Enable drawer layout
public void enableDrawerLayout() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//!< Set custom action bar title
public void setActionBarTitle(String title){
tvActionBarTitle.setText(title);
}
//!< Return MainActivity object
public MainActivity getMainActivity() {
mainActivity = new MainActivity();
return mainActivity;
}
//!< This hook is called whenever an item in your options menu is selected. . The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//!< Sync the toggle state after onRestoreInstanceState has occurred. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
//!< Pass any configuration change to the drawer toggles. This method should always be called by your Activity's onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
//!< Call respective fragment
public void selectItem(int position) {
switch (position) {
case 0:
fragment = new FragmentTwo();
break;
case 1:
fragment = new FragmentThree();
break;
case 2:
finish();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
}
Drawer layout code:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/lv_drawer"
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#000000"/>
</android.support.v4.widget.DrawerLayout>
Drawer layout listview laout code:
<?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="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:id="#+id/itemLayout">
<TextView
android:id="#+id/tv_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Action bar layout code:
<?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="#android:color/transparent" >
<TextView
android:id="#+id/tv_action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</RelativeLayout>
1st fragment code:
public class FragmentOne extends Fragment {
ImageView ivIcon;
TextView tvAgentID;
public Typeface officialBoldFont, officialRegularFont;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container, false);
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag one list item 1", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragOneClickListener());*/
//
officialRegularFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedbold.ttf");
tvAgentID = (TextView) view.findViewById(R.id.tv_agentid);
tvAgentID.setText("TESTING 1 2 3");
tvAgentID.setTypeface(officialBoldFont);
tvAgentID.setTextColor(Color.BLACK);
tvAgentID.setBackgroundColor(Color.WHITE);
tvAgentID.setTextSize(25f);
return view;
}
}
1st fragment layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<LinearLayout
android:id="#+id/ll_innerloginlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:padding="20dp">
<TextView
android:id="#+id/tv_agentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2nd fragment code below:
public class FragmentTwo extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
private List<DrawerLayoutDrawer> dataList;
public FragmentTwo()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_two, container, false);
//
((MainActivity) getActivity()).setActionBarTitle("Test screen 2");
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag two list item 2", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragTwoClickListener());*/
ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
tvItemName=(TextView)view.findViewById(R.id.frag2_text);
tvItemName.setText("TESTING FRAG TWO");
tvItemName.setTextSize(45f);
tvItemName.setTextColor(Color.RED);
tvItemName.setBackgroundColor(Color.BLACK);
return view;
}
}
2nd fragment XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag2_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="200dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="0dp"/>
</LinearLayout>
3rd fragment code:
public class FragmentThree extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentThree()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_three, container, false);
ivIcon=(ImageView)view.findViewById(R.id.frag3_icon);
tvItemName=(TextView)view.findViewById(R.id.frag3_text);
tvItemName.setText("TESTING FRAG THREE");
return view;
}
}
3rd fragment XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag3_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag3_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
1st fragment listener:
public class FragOneClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragOneSelectItem(position);
}
}
2nd fragment listener:
public class FragTwoClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragTwoSelectItem(position);
}
}
I'm working on an Application which contains a PageViewer inside a Layout.
But if i start it, the PageViewer isn't visible. (looks leight layout_height=0)
I never used a PageViewer inside other layouts, so maybe it isn't designed to be part of something?
Layout file (shortened,activity_tricks.xml):
<linearLayout>
<TableRow>
....
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrapt_content">
<android.support.v4.view.ViewPager
android:id="#+id/Activity_Trick_viewPager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="6dip" />
</TableRow>
<TableRow>
.
.
.
Trick_Fragment_layout.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:orientation="vertical" >
<TextView
android:id="#+id/trick_fragment_textView_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Activity:
public class TrickActivity extends FragmentActivity {
private ViewPager mViewPager;
private TrickActivityPageAdapter mPageAdapter;
public static final int FRAMES = 3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tricks);
mPageAdapter= new TrickActivityPageAdapter(getSupportFragmentManager(),frames);
mViewPager=(ViewPager)findViewById(R.id.Activity_Trick_viewPager);
mViewPager.setAdapter(mPageAdapter);
//... do other stuff.. //
}
}
public class TrickActivityPageAdapter extends FragmentPagerAdapter {
private int frames;
public TrickActivityPageAdapter(FragmentManager fm, int frames) {
super(fm);
this.frames = frames;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TrickFragment.init("F 1");
case 1:
return TrickFragment
.init("F 2");
case 2:
return TrickFragment.init("f3");
default:
return TrickFragment.init("default");
}
}
#Override
public int getCount() {
return frames;
}
}
public class TrickFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static Fragment init(String string) {
TrickFragment f = new TrickFragment();
Bundle bdl = new Bundle();
bdl.putString(EXTRA_MESSAGE, string);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.trick_fragment_layout, container, false);
TextView tv = (TextView)v.findViewById(R.id.trick_fragment_textView_1);
tv.setText(message);
return v;
}
I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<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.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<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/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.
Just started learning android. Help please. I have three fragments, each has a button that must run one of the streams of the media player. How can I find the button of my activity in the fragment that would later attach to it a specific stream?
Tried to make a reference to the button so that:
btnStart = (Button) titleAdapter.frags[0].getView().findViewById(R.id.btnStart);
Did not work, an error java.lang.NullPointerException, what I'm doing wrong
public class TitleAdapter extends FragmentPagerAdapter {
private final String titles[] = new String[] { "FragA", "FragB", "FragC" };
private final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
code MainActivity.java:
public class MainActivity extends FragmentActivity {
final static String LOG_TAG = "myLogs";
static MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
static Button btnNews;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
pdaStream = (CheckBox) findViewById(R.id.pdaStream);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
initBar(music, AudioManager.STREAM_MUSIC);
}
#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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.news:
Intent intent = new Intent(this, RSSActivity.class);
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public static void initBar(SeekBar bar, final int stream) {
bar.setMax(am.getStreamMaxVolume(stream));
bar.setProgress(am.getStreamVolume(stream));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
am.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
}
public void onStartTrackingTouch(SeekBar bar) {
// no-op
}
public void onStopTrackingTouch(SeekBar bar) {
// no-op
}
});
}
}
code fragments similar, here's one of them
code FragmentA.java:
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
private static ProgressBar progressBar;
static CheckBox pdaStream;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
final Button Play = (Button) rootView.findViewById(R.id.btnStart);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
pdaStream = (CheckBox) getActivity().findViewById(R.id.pdaStream);
return rootView;
} }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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"
android:background="#drawable/background"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#drawable/bg_pager"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:thumb="#drawable/seek" />
<CheckBox
android:id="#+id/pdaStream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="70dp"
android:text="#string/chkbox" />
</RelativeLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStart"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="16sp"
android:onClick="onClick"
android:background="#drawable/play_button"/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
public static Fragment getCurrentFragment(ViewPager pager, FragmentPagerAdapter adapter) {
try {
Method m = adapter.getClass().getSuperclass().getDeclaredMethod("makeFragmentName", int.class, long.class);
Field f = adapter.getClass().getSuperclass().getDeclaredField("mFragmentManager");
f.setAccessible(true);
FragmentManager fm = (FragmentManager) f.get(adapter);
m.setAccessible(true);
String tag = null;
tag = (String) m.invoke(null, pager.getId(), (long) pager.getCurrentItem());
return fm.findFragmentByTag(tag);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
Then put a public getter for button in FragmentA.java,
public Button getPlayButton()
{
return Play;
}
in your Fragment activity,
Fragment currenFragment = getCurrentFragmet(mViewPager,titleAdapter);
if(currenFragment!=null){
// cast the fragment to FragmentA class, then call getter
((FragmentA)currentFragment).getPlayButton();
}
use following code in onActivityCreated() of fragment
btnStart = (Button) getView().findViewById(R.id.btnStart);