I am trying to attain Tab feature using simple Buttons
What is happening now::
Click on Button1 ----> F1 Activity is displayed
Click on button1 (again) ---- > F2 Activity is isplayed
Click on Button1 (third time) -----> F1 Activity is Displayed
again
-
Similarly with Button2 w.r.t G1 & G2 activities
FragmentDemo.java
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
F1.java
public class F1 extends Fragment {
Context c;
View v;
public F1(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f1, container, false);
return v;
}
}
F2.java
public class F2 extends Fragment {
Context c;
View v;
public F2(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f2, container, false);
return v;
}
}
Similarly for G1 & G2
activity_fragment_demo.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=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
</LinearLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
OUTPUT::
Clearly we can see that, when i start the project i come to blank screen ..... A default activity is not displayed. As it does in Tabs
How can i make sure a default activity say F1 be already be present when i load the project
Like this ::
Any ideas
What changes should i need to make in the code
Hope i am clear
Your Layout activity_fragment_demo looks good so I will use that. The LinearLayout with id simple_fragment will be the container that holds the fragment's view
So lets say that the fragment F1 represents your first Tab and the fragment F2 represents your second tab.
So three methods that you should have are.
The following method adds each fragment to the activity and has to be called for both F1 and F2 in the activity's onCreate
public void addFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, fragment);
}
The following method essentially shows a fragment.I am not sure about the behind workings of attach but it can be seen as View.VISIBLE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.attach(fragment).commit();
}
The following method essentially hides a fragment.I am not sure about the behind workings of detach but it can be seen as View.GONE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.detach(fragment).commit();
}
Your Activity's onCreate method
public void onCreate()
{
//Create all your fragments here eg F1 f1 = new F1(); etc
//For whatever fragment you have created you should call the method addFragment
//Now depending on what fragment you want shown by default you should call attachFragment or detachFragment. eg. if F1 has to be shown by default
attachFragment(F1);
detachFragment(F2) //and all otherfragment you want hidden by default
//Set the listeners for the buttons
//The purpose of the next two lines is to store the current state of the buttons. Since F1 is attached to button1 and it is currently being shown we set the tag to "clicked"
//and button2 tag has been set to notClicked
button1.setTag("clicked");
button2.setTag("notClicked");
}
Inside the onClickListener for your buttons
OnClickListener onTabButtonClickListener = new OnClickListener()
{
public void onClick(View view)
{
switch(view.getId)
{
case R.id.button1
{
if(button1.getTag().equals("clicked"))
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("notClicked");
button2.setTag("clicked");
}
else
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("clicked");
button2.setTag("notClicked");
}
}
case R.id.button2
{
//Same thing as before except opposite
}
}
}
}
And that should work.I am not very good at explaining stuff so feel free to ask any questions you have.
With the suggestion user1950599 in his comment he gave ..... i achieved this
just one line of updating was required
Sharing this might help someone
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
Related
How to add action bar in YouTube player?
I'm trying to add action bar in this activity, but because it's not extended to AppCompatActivity that's why I'm getting an error in getSupportActionBar();. I'm also getting error if I replace the YouTubeBaseActivity with AppCompatActivity. Can anyone help me with this?
public class ActivityPlayer extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public String DEVELOPER_KEY = "key";
public String YOUTUBE_VIDEO_CODE = "5z-Roo_NpI4";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubeView.initialize(DEVELOPER_KEY, this);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return true;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
Snackbar.make(youTubeView, "There was an error initializing the video player.", Snackbar.LENGTH_LONG).setDuration(5000).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.loadVideo(YOUTUBE_VIDEO_CODE);
player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
#Override
public void onBackPressed() {
finish();
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_player);
}
}
I had the same Problem with you, I'm posting an answer in case you or others still need a work around. Forget about YoutubeBaseActivity and focus on YoutubePlayerSupportFragment because Fragment let you setup your Activity as you wish. There is YoutubePlayerFragment also but the Support version of it work better with android support libraries.
Here's is the Steps I used :
Make your activity Extends AppCompatActivity
public class ActivityPlayer extends AppCompatActivity {
Add a FrameLayout in xml layout of the Current Activity that extends AppCompatActivity (activity_main.xml)
<FrameLayout
android:id="#+id/flYoutube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:visibility="visible" />
Create a YoutubeFragment extends Fragment, with fragment_youtube.xml layout and a FrameLayout inside of it. And in onCreateView, create a YoutubePlayerSupportFragment instance and replace the FrameLayout within the fragment_youtube.xml with that instance of YoutubePlayerSupportFragment.
public class YoutubeFragment extends Fragment {
private static final String YOUTUBE_API_KEY = "8S7K4hEVhgOQ87501j-FAKE-KEY";
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String VIDEO_ID = "VIDEO_ID";
// TODO: Rename and change types of parameters
private String videoId;
public YoutubeFragment() {
// Required empty public constructor
}
public static YoutubeFragment newInstance(String videoId) {
YoutubeFragment fragment = new YoutubeFragment();
Bundle args = new Bundle();
args.putString(VIDEO_ID, videoId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
videoId = getArguments().getString(VIDEO_ID);
}
}
#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.replace(R.id.flYoutubePlayer, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize(YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
//youTubePlayer.setFullscreen(true);
youTubePlayer.loadVideo(videoId);
//yoTubePlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
return rootView;
}
}
Create a 2nd FrameLayout in fragment_youtube.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="jfsl.ayibopost.fragments.YoutubeFragment">
<FrameLayout
android:id="#+id/flYoutubePlayer"
android:layout_width="match_parent"
android:layout_height="200dp"></FrameLayout>
</RelativeLayout>
Last thing to do in PlayerActivity onCreate(), is to create an instance of your own created YoutubeFragment and replace the Frame Layouts within the activity_main.xml with that YoutubeFragment instance via Fragment Transaction:
// Create Youtube Fragment instance by passing a Youtube Video ID
YoutubeFragment youtubeFragment = YoutubeFragment.newInstance("2zNSgSzhBfM");
getSupportFragmentManager().beginTransaction()
.replace(R.id.flYoutube, youtubeFragment).commit();
And you are done.
You should implement an AppCompatCallback interface.
Please, see my answer.
I would like to select few players ( highlighted in purple colors ie Player 1, Player 3 & Player 5) from 'MyPlayerActivity' and add these selected players into a mapbox Map as markers (MainActivity) during on click on 'Add Player' button.
Could someone please help me on how to achieve this ?
Following is my 'MyPlayerActivity' code
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" + players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#+id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="#+id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="#string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(#NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("\nTelemetryService is not configured in your applications AndroidManifest.xml. " +
"\nPlease add \"com.mapbox.mapboxsdk.telemetry.TelemetryService\" service in your applications AndroidManifest.xml" +
"\nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
To add a marker to the map you can use this snippet:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
If the listview and map are in separate activities, you can pass the selected player information to the map activity using an intent. Is this what you were looking for?
I have a FloatingActionButton inside of may activity_main.xml layout which is named fabBtn.
My application is built with a ViewPager and three Fragments.I want to hide the FloatingActionButton when my first Fragment detects a scroll, but I keep getting a NullPointerException if the user starts scrolling.
I believe it could be that my fragment can't get the FloatingActionButton from the activity_main.xml layout?
Here is my activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lh.com.newme.MainActivity"
xmlns:fab="http://schemas.android.com/tools">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|snap"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabMode="fixed"
app:layout_scrollFlags="snap|enterAlways"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#ffffff" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabBtn"
android:layout_marginBottom="#dimen/codelab_fab_margin_bottom"
android:layout_marginRight="#dimen/codelab_fab_margin_right"
android:layout_width="wrap_content"
fab:fab_type="normal"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
app:backgroundTint="#color/fab_ripple_color"
android:src="#drawable/ic_plus"
app:fabSize="normal"
/>
</android.support.design.widget.CoordinatorLayout>
Here is my first Fragment from where I want to hide the FloatingActionButton:
public class Ernaehrung extends Fragment {
NestedScrollView nsv;
FloatingActionButton fab;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
final View rootView = inflater.inflate(R.layout.ernaehrung, container, false);
Button Fruehstuck = (Button) rootView.findViewById(R.id.fruehstuck);
Button Mittagessen = (Button) rootView.findViewById(R.id.mittagessen);
Button Snacks = (Button) rootView.findViewById(R.id.snacks);
Fruehstuck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent FruehstuckScreen = new Intent(getActivity(), lh.com.newme.Fruehstuck.class);
startActivity(FruehstuckScreen);
}
});
Mittagessen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent MittagScreen = new Intent(getActivity(), lh.com.newme.Mittagessen.class);
startActivity(MittagScreen);
}
});
Snacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SnackScreen = new Intent(getActivity(), lh.com.newme.Snacks.class);
startActivity(SnackScreen);
}
});
nsv = (NestedScrollView)rootView.findViewById(R.id.Nsv);
fab = (FloatingActionButton)rootView.findViewById(R.id.fabBtn);
nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (oldScrollY < scrollY){
fab.hide();
}
else
fab.show();}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.main_menu_ernaehrung, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
int id = item.getItemId();
if (id == R.id.benutzer){
}
return super.onOptionsItemSelected(item);
}
}
This is my MainActivity.class :
public class MainActivity extends AppCompatActivity {
FloatingActionButton fabBtn;
CoordinatorLayout rootLayout;
Toolbar toolbar;
TabLayout tabLayout;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.show();
...
break;
case 1:
fab.show();
...
break;
case 2:
fab.hide();
break;
default:
fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
initInstances();
}
private void initInstances() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
rootLayout = (CoordinatorLayout) findViewById(R.id.rootLayout);
fabBtn = (FloatingActionButton) findViewById(R.id.fabBtn);
}
#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_edit, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.einstellungen) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
First of all, change your line
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
to
fabBtn = (FloatingActionButton)findViewById(R.id.fabBtn);
Solution #1 - get view (if you need object)
Then, in your MainActivity add getter for your FloatingActionButton, like
public FloatingActionButton getFloatingActionButton {
return fabBtn;
}
Finally, in your Fragment call:
FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();
and
if (floatingActionButton != null) {
floatingActionButton.hide();
}
or
if (floatingActionButton != null) {
floatingActionButton.show();
}
Solution #2 - add two methods in MainActivity (if you need only specific methods, like show() / hide())
public void showFloatingActionButton() {
fabBtn.show();
};
public void hideFloatingActionButton() {
fabBtn.hide();
};
And in your Fragment call to hide:
((MainActivity) getActivity()).hideFloatingActionButton();
or to show:
((MainActivity) getActivity()).showFloatingActionButton();
Note
If you use more than one Activity, you must check if it's proper Activity:
if (getActivity() instanceof MainActivity) {
getActivity().yourMethod(); // your method here
}
In your fragment your rootView layout is not main layout and you cannot expect the rootView will return the fab button. Thats why you are getting null pointer exception
You better use interface to detect page scrolling and controll it via your activity
i have a navigation drawer in my app and i am trying to use its content which is a simple counter.whenever i click on the counter my app crashes my logcat shows view not found etc etc.here are my three files start.java is my main java file,fragtasbeeh is my counter fragment and xml file.thnx in advance:
public class Start extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#076672")));
setContentView(R.layout.activity_start);
// Initializing
dataList = new ArrayList<DrawerItem>();
mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.leftdrawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Search", R.drawable.ic_action_map));
dataList.add(new DrawerItem("compass",
R.drawable.ic_action_location_found));
dataList.add(new DrawerItem("counter", R.drawable.ic_action_good));
dataList.add(new DrawerItem("tings", R.drawable.ic_action_group));
dataList.add(new DrawerItem("about us", R.drawable.ic_action_about));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(-1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
public void SelectItem(int possition) {
if(possition==-1)
{
setTitle(getResources().getString(R.string.app_name));
}
else{
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 1:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 2:
fragment = new FragTasbeeh();
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
public class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
SelectItem(position);
}
}
}
Fragtasbeeh.java
public class FragTasbeeh extends Fragment implements OnClickListener{
int count;
Button reset,add;
TextView counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.tasbeeh, container,true);
reset=(Button) v.findViewById(R.id.reset);
add=(Button)v.findViewById(R.id.count);
counter=(TextView)v.findViewById(R.id.editText1);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=count+1;
counter.setText(count);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=0;
counter.setText(count);
}
});
return v;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
tasbeeh.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" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
android:maxHeight="60dp"
android:textColor="#076672" >
<requestFocus />
</EditText>
<Button
android:id="#+id/reset"
android:layout_width="117dp"
android:layout_height="20dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="0.35"
android:paddingLeft="50dp"
android:text="#string/RESET"
android:textAlignment="center"
android:textSize="20dp" />
<Button
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="0.85"
android:text="count" />
</LinearLayout>
the problem was with the xml file, there was a space or alignment problem between button and textview
ive solved it by making a relativelayout
from within a MapFragment I'd like to display some kind of settings window. What would be the best way to do that?
Replace the fragment? Create some kind of overlaying view? AlertDialog?
How would I best implement it?
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//...
}
});
Thanks
Put the settings in a diaglog fragment activated from button in the actionbar have an interface so you can update the map in background.
See this live in my app
Button in action bar.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_settings"
android:icon="#drawable/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
android:showAsAction="always"
yourapp:showAsAction="always"/>
Process the button click
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int x = item.getItemId();
switch (x) {
case R.id.action_settings:
showSettingsDialog();
return true;
do something useful show the fragment.
private void showSettingsDialog() {
FragmentManager fm = getSupportFragmentManager();
MapSettings editSettingsDialog = new MapSettings();
editSettingsDialog.show(fm, "fragment_edit_name");
}
The complete mapsettings class.
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
getDialog().setTitle(R.string.app_name);
View view = inflater.inflate(R.layout.activity_map_settings, container);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
// initialize to the shared preferences value
rg.clearCheck();
... homemade glue to get the initial setting.
GoPreferences.getInt(getActivity(),MAP_TYPE,GoogleMap.MAP_TYPE_NORMAL);
RadioButton rb = null;
switch (x) {
case GoogleMap.MAP_TYPE_HYBRID:
rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_NORMAL:
rb = (RadioButton) view.findViewById(R.id.RDORoad);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
rb.setChecked(true);
break;
}
// set the listener after setting up
rg.setOnCheckedChangeListener(this);
return view;
}
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
// save the settings
}
impliment the interface on your map activity so the map can be changed from the dialog fragment.
public class KmlReader extends ActionBarActivity implements
BestRidesSettingsDialogListener, SnapshotReadyCallback,
OnMapLoadedCallback {
#Override
public void onMapSettingsChange(int mapType) {
// TODO Auto-generated method stub
if (mMap != null) {
mMap.setMapType(mapType);
}
}
Good Luck
Danny117