add Spinner to action bar in Fragment in Android - android-spinner

Could any one tell me, how to add Spinner to action bar in Fragment ?

I solved that issue by using below steps
Step - 1
Create xml file in Layout folder(Consider Layout name is spinnerwound.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="fill_parent"
android:background="#F79D27"
android:orientation="vertical">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"/>
</LinearLayout>
Step - 2
In Fragment Write like this
((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(true);
LayoutInflater inflator = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflator.inflate(R.layout.spinnerwound, null);
Spinner s = (Spinner) vi.findViewById(R.id.spin);
spinnerlist = new ArrayList<String>();
spinnerlist.add(Item1);
spinnerlist.add(Item2);
spinneradapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_dropdown_item_1line, spinnerlist);
s.setAdapter(spinneradapter);
((ActionBarActivity)getActivity()).getSupportActionBar().setCustomView(vi);
spinneradapter.notifyDataSetChanged();
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//Do what ever you want
}

Related

popup window on my map Fragment android studio

can anyone help me with this i want to show a popupwindow on top of my map fragment when i click on a button it will display a popupwindow that contains text for example the text will be how the user will navigate the map
public class FirstFragment extends Fragment {
public FirstFragment() {
// require a empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(new OnMapReadyCallback() {
public void onMapReady(#NonNull GoogleMap googleMap) {
GoogleMap mMap = googleMap;
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(requireContext()));
mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(requireContext(), R.raw.style));
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(14.5768, 121.0332))
.zoom(15)
.bearing(0)
.tilt(60)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 4000, null);
mMap.addMarker(new MarkerOptions()
.icon(bitmapDescriptorFromVector(getActivity(), R.drawable.ic_baseline_location_city_24))
.position(new LatLng(14.5768, 121.0332))
.title("Mandaluyong");
KmlLayer layer = null;
try {
layer = new KmlLayer(mMap, R.raw.mandaluyong, getContext());
} catch (Exception e) {
e.printStackTrace();
}
for (KmlPlacemark placemark : layer.getPlacemarks()) {
}
layer.addLayerToMap();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions()
.position(point)
.title("Home")
.snippet("Your PlaceMarker!!!"));
this is the xml file i've added a floating action button on it now when click it i want to display a popup window that will show on top of my map fragment ive tried different things and it crashes or doesnt show the popup ive decided to ask here because i am stuck in this part
}
<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=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res-auto">
<fragment
android:id="#+id/maps"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/infobutton"
android:src="#drawable/ic_baseline_info_24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="97dp"
android:clickable="true"
android:rotation="0" />
<FrameLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="300dp">
</FrameLayout>
</RelativeLayout>
here are the java and xml files of the map fragment that i used
[maps app pic][1]
[1]: https://i.stack.imgur.com/xaBIR.png

Android: RecyclerView's CardView Not Showing Every Time

I have a RecyclerView in MainActivity that shows a list of CardViews and that is working properly. A click on the CardView finishes the RecyclerView Activity and launches a Detail Activity that shows the clicked on CardView in a new RecyclerView list. The Detail Activity is used only to show that single CardView in a RecyclerView (I do this so I can use RecyclerView's ItemTouchHelper.SimpleCallback code on the CardView for easy left swipe for the user).
Here is the problem: I hit the left caret on the Detail Activity's Toolbar to return to the MainActivity. Then a click on the exact same CardView brings the user back to the Detail Activity. But this time only the background View (a border) is showing. The view of the CardView and its database data is completely missing.
The error appears to happen randomly. I can click to go from the MainActivity to the Detail Activity back and forth 5 times successfully and then on the sixth try, no CardView will show in the Detail Activity. Or I'll click two times successfully and then the third time, the CardView in the Detail Activity will not show. Note the left caret click in Detail Activity uses onBackPressed() so the Detail Activity finishes. So I don't think there should be any backstack issues. I also tried to adjust the xml height for the CardView to match_parent rather than wrap_content but no luck. The Detail Activity's ViewModel to Repository to Dao returns a List wrapped in LiveData. Perhaps there is an observer problem with the ViewModel, but I thought the observer gets removed/destroyed when the Detail Activity is destroyed? What am I missing here?
Adapter
...
itemHolder.cardView.setOnClickListener(view -> {
Card adapterItem= TodosAdapter.this.getItem(itemHolder.getAdapterPosition());
int adapPos = itemHolder.getAdapterPosition();
if (adapPos !=RecyclerView.NO_POSITION) {
onItemClick(adapPos, adapterItem);
}
});
MainActivity
...
public void onItemClick(int clickPos, Card cardFromClick) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("TAG","fromMain");
intent.putExtra("itemFromMain", cardFromClick);
startActivity(intent);
finish();
DetailActivity
...
public class DetailActivity extends AppCompatActivity {
private int cardId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// Get a new or existing ViewModel from the ViewModelProvider.
detsViewModel = new ViewModelProvider(this).get(CardViewModel.class);
Toolbar toolbar = findViewById(R.id.toolbar);
// The left caret is for Up navigation to the previous activity
// for OS versions 4.0 and earlier.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_previous_item);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
String classname = extras.getString("TAG");
// The user clicked on a Card in the MainActivity
if (classname != null && classname.equals("fromMain")) {
card = extras.getParcelable("itemFromMain");
if (card != null) {
cardId = card.getId(); // card data is stored in Room database.
}
}
}
detsViewModel.getSingleCard(cardId).observe(this, singleAdapterList -> {
adapter2.setCardList(singleAdapterList);
});
}
activity_details.xml
...
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
tools:context=".DetailsActivity" >
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" >
</include>
<RelativeLayout
android:id="#+id/todoListLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" >
<TextView
android:id="#+id/Card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="Card"
android:textStyle="bold"
android:textColor="#color/text_primary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/details_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/Card"
android:scrollbars="vertical" />
<TextView
android:id="#+id/skytext5"
android:text="Cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/details_recyclerview"
android:background="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:clickable="true"
android:focusable="true" />
</RelativeLayout>
DetailsAdapter
...
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.details_list_item, parent, false);
}
private List<Card> oneCardList
public void setCardList(List<Card> singleCardList) {
if (oneCardList != null) {
oneCardList.clear();
this.oneCardList = singleCardList;
} else {
// First initialization
this.oneCardList = singleCardList;
}
}
details_list_item.xml
...
<FrameLayout
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/detsinglecard_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:foreground="?android:attr/selectableItemBackground"
android:background="#FFFFFF"
tools:context=".DetailActivity">
<RelativeLayout
android:id="#+id/view_background2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
...
</RelativeLayout>
<RelativeLayout
android:id="#+id/view_foreground2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/colorFlLabelFinal" >
<androidx.cardview.widget.CardView
android:id="#+id/cardview_dets"
android:layout_height="match_parent"
android:layout_width="match_parent"
...
}
ViewModel
...
LiveData<List<Card>> getSingleCard(int cardId) {
return repository.getSingleCard(cardId);
}
Repository
...
public LiveData<List<Card>> getSingleCard(int cardId) {
return quickcardDao.getSingleCard(cardId);
}
Dao
...
#Query("SELECT * FROM cards WHERE cardId = :cardId LIMIT 1")
LiveData<List<Card>> getSingleCard(int cardId);
So if the data does not change then going back to the same DetailActivity will not refresh the View. The answer was to re-use the LiveData (rather than re-loading the LiveData again from the database) if the data has not changed. See the Android Developers Architecture Components guide for ViewModel, "Implement a ViewModel" section for the "loadUsers()" example that solved my problem: https://developer.android.com/topic/libraries/architecture/viewmodel.

Display Image In Android Studio On Device Connected Externally

I am new to Android Learning. I am trying to make a customAdapter that will display an image and a text in every row. In my Main_Activity, I have following code:`
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String [] foods= {"Biryani","Matar Qeema","Chicken"};
ListAdapter faizisAdapter= new CustomAdapter(this,foods);
ListView faizisListView= (ListView)findViewById(R.id.faizisListView);
faizisListView.setAdapter(faizisAdapter);
faizisListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String food= String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(MainActivity.this,food,Toast.LENGTH_LONG).show();
}
});
}
}
Here is my CustomAdapter:
class CustomAdapter extends ArrayAdapter<String>{
CustomAdapter(Context context, String []foods)
{
super(context,R.layout.custom_row, foods);
}
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
LayoutInflater faisizInflater = LayoutInflater.from(getContext());
View faizisView = faisizInflater.inflate(R.layout.custom_row, parent,
false);
String food = getItem(position);
TextView _foodsDisplay = (TextView)
faizisView.findViewById(R.id._foodDisplay);
ImageView _imageDisplay = (ImageView)
faizisView.findViewById(R.id._imageDisplay);
_imageDisplay.setImageResource(R.drawable.zaheer8423);
_foodsDisplay.setText(food);
return faizisView;
}
}
My Main_Activity_XML_FILE is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/faizisListView"
>
</ListView>
XML_FILE_FOR_customAdapter:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/_imageDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/zaheer8423"
/>
<TextView
android:id="#+id/_foodDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
I haved saved image file in app/src/main/res/drawable/zaheer8423.jpg. I have connected my android device with android studio externally. When I run the app It opens and suddenly closes.
I have seen ways that use bitmap but I could not use them effectively, because I have very little knowledge about them.
Please help me here.
Looks like your Image size is big,You might need to scale down image something like this.
// Decode with inSampleSize
BitmapFactory.Options option = new BitmapFactory.Options();
option.inSampleSize = scale;
//You need to calculate appropriate sample size
Bitmap bitmap =
BitmapFactory.decodeResource(getContext().getResources(),R.drawable.zaheer8423,option);
imageDisplay.setImageBitmap(bitmap);
As its adapter you need to manage caching the bitmap and creating bitmap should be done in worker thread (Non Main thread i.e. UI Thread ) to avoid ANRs.

Android Floating Action Button Behaviour with Adview

I'm sorry if this has been already answered but it's been a while and I'm still searching. Since the FAB has a behaviour class you can assign to it which will work with scrolling inside a coordinator layout, I was wondering if it was possible to include behaviour to make the FAB automatically get placed above an adview when it is visible similar to how it reacts to a snack bar. Thank you in advance.
Work Around!
I figured out a work around as I was just playing around some time back, even forgot about the question. Instead of putting my adview inside a container with the rest of my views I simply had to wrap the coordinator view in a Relative layout and set the coordinator layout above the adview ID. I'm sure this might not be the best way to do it.
So what I ended up having is this: NB My adview is set to visibility gone by default and I only set the visibility when the adrequest is complete
<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">
<android.support.design.widget.CoordinatorLayout
android:layout_above="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<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/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:visibility="gone"
app:layout_behavior="utils.FabBehavior_Main"
app:rippleColor="#color/fab_ripple"
app:srcCompat="#drawable/ic_fab" />
</android.support.design.widget.CoordinatorLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/ad_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone"
app:adSize="SMART_BANNER"
app:adUnitId="#string/banner_ad_unit_id"
/>
</RelativeLayout>
The utils.FabBehavior_Main is the relative package class that contains the behaviour properties for the view, utils being the package. So in your own application you could have the name space com.myapp.utils.ScrollAwareFab which would have be like this:
public class ScrollAwareFab extends FloatingActionButton.Behavior {
public ScrollAwareFab(Context context, AttributeSet attrs) {
super();
}
#Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
#Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child,
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed,
dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
child.hide(new FloatingActionButton.OnVisibilityChangedListener() {
/**
* Called when a FloatingActionButton has been hidden
*
* #param fab the FloatingActionButton that was hidden.
*/
#Override
public void onHidden(FloatingActionButton fab) {
super.onShown(fab);
fab.setVisibility(View.INVISIBLE);
}
});
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
child.show();
}
}
}

Receive a long press/click on a linear layout in android?

I'm painfully new to android and I've run into a wall.
I'm trying get a linear layout to function more like a button, with different actions for press and long press - The reason being so I can have 2 differently formatted text labels on each "button". Something along the lines of:
-------------------------
| 2nd | <- Label for long press (regular/smaller type)
| = | <- Label for regular press (bold/larger type)
-------------------------
The posts I've found explain how to receive a regular click on a linear layout (I use the onClick attribute in the layout XML). But I've had no luck with long press. I've tried to define a new onLongClick attribute for xml as described in Aleksander Gralak's answer here: Long press definition at XML layout, like android:onClick does . But had no such luck - it looks like it was intended for a text view, I tried changing it to linear layout but failed miserably.
Here is the object in question: Main.xml
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:background="#drawable/darkgrey_button"
android:onClick="equals" android:longClickable="true" android:id="equalsbutton"
android:focusableInTouchMode="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2nd"
android:id="#+id/textView"
android:duplicateParentState="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" = "
android:id="#+id/textView1"
android:duplicateParentState="true"/>
</LinearLayout>
And Main.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void equals(View view) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Add an id to your layout.
<LinearLayout
android:id="#+id/my_button_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
… >
In your Main.java
Get a reference to your LinearLayout and set a OnLongClickListener.
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.my_button_layout);
…
buttonLayout.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(Main.this, "Long click!", Toast.LENGTH_SHORT).show();
return true;
}
});

Resources