Dynamically created TextView in FrameLayout has no width - java

I'm trying to add a TextView in code to a framelayout. This sits above an imageview in the z order of the framelayout. The ultimate aim is to allow the creation of a screenshot from the framelayout that shows the image and the text that has been overlayed on to it. I have this working when using a textview created in xml but not in the dynamic code version. The create bitmap method returns an error complaining about the width of the textbox being 0. In the code below I am trying to capture just the textview as an image to identify what the issue is, as the captured image from the framelayout did not contain the contents of the textview as expected. In doing this I was able to find the width error and I believe it is this that is the root of the problem. I have tried to set the textview's width using setWidth and also using the LayoutParams. The end result is always that the textview has no width although it can be seen on the handset clearly. I think I am missing something between the dynamic creation and the existing xml which results in the 0 width. Can anyone point me in the correct direction please?
The code is as follows
public void applyTextToImage(View view) {
// Do something in response to button
//Hide the virtual keyboard
InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//Get the text to overlay on the image
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
//Bring the overlay layout to the front
//LinearLayout overlay_layout = (LinearLayout) findViewById(R.id.image_Overlay_Layout);
//overlay_layout.bringToFront();
//Apply the new text to the text box
/* Old code to get the view that is shown in the layout
TextView text_overlay = (TextView) findViewById(R.id.image_Overlay);
text_overlay.bringToFront();
text_overlay.setText(message);
*/
//New code to create a view dynamically instead
TextView text_Overlay = new TextView(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
text_Overlay.setId(Utils.generateViewId());
}
else
{
text_Overlay.setId(TextView.generateViewId()); //static class
}
FrameLayout image_Layout = (FrameLayout) findViewById(R.id.image_Layout);
//View image_Layout = (View) findViewById(R.id.image_Layout);
//FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams fParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.WRAP_CONTENT);
fParams.gravity = Gravity.CENTER;
// text_Overlay.setMaxWidth(image_Layout.getWidth());
// text_Overlay.setWidth(image_Layout.getWidth());
//image_Layout.addView(text_Overlay, fParams);
image_Layout.addView(text_Overlay, fParams);
Toast.makeText(this,"TextView Width: " + text_Overlay.getWidth(),Toast.LENGTH_LONG).show();
//TODO: Something has forced the dynamic layout to not be saved in the bitmap try removing the params and set the values on the textview itself
//TODO: for some reason the width keeps coming back as 0 could be that the image_Layout is 0 too
text_Overlay.setGravity(Gravity.CENTER);
text_Overlay.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
//text_Overlay.setWidth(250dp);
text_Overlay.setTextSize(pixels);
text_Overlay.setTextColor(Color.RED);
text_Overlay.bringToFront();
text_Overlay.setText(message);
text_Overlay.setVisibility(View.VISIBLE);
//End of new dynamic code
if (folderCheck()){
try {
String filePath = getFilePath();
int myId = text_Overlay.getId();
Bitmap bitmap;
View v1 = findViewById(myId);
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache();
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
// End imported code
streamBitmapToFile(bitmap, filePath);
}
catch (Exception e)
{
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG);
Log.e("Bitmap Creation","Couldn't create bitmap error as: " + e.toString());
}
}
}
XML contents
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout 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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="false">
<!--app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_my"-->
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
android:enabled="false"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="applyTextToImage"
android:enabled="false"
android:id="#+id/overlayButton"/>
</LinearLayout>
<FrameLayout
android:id="#+id/image_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true">
<ImageView
android:id="#+id/image_View"
android:layout_width="match_parent"
android:layout_height="250dp" />
<!--<TextView
android:id="#+id/image_Overlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:textSize="25dp"
android:textColor="#ff0000"/>-->
</FrameLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/open_gallery"
android:onClick="openGallery">
</Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_image"
android:onClick="newImage">
</Button>
</LinearLayout>
</RelativeLayout>

The view has not been measured yet. Until the system does another layout pass, the view reports its width as zero.
In my opinion, you are better off leaving the TextView in the XML layout and simply making it invisible (android:visibility="invisible") until you need it, then make it visible prorammatically with setVisbility(View.VISIBLE). (Note that if you set it to be gone, it will also not be measured.)

For reference Karakuri pointed out the weaknesses and the path to follow to resolve them.
Extra code that was implemented for the listener is as follows.
IMAGE_CAPTURE_REQUESTED = true;
// New Listener
ViewTreeObserver vto = image_Layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
image_Layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else
{
image_Layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
if (IMAGE_CAPTURE_REQUESTED) {
//int myId = text_Overlay.getId();
//Toast.makeText(MyActivity.this, "Text Overlay Width " + text_Overlay.getWidth() ,Toast.LENGTH_LONG).show();
overlayTextAndExportImage();
}
}
}); //End New Listener
The new overlayTextAndImportImage calls all the image creation routines after the layout has been redrawn.

Related

Android, Can't change textView when use getLayoutInflater()

I'm trying to set text in the tooltip inside my layout but It's now working, what I did is get the tooltip layout using getLayoutInflater() and get the textView then assign a new value to it, but this is not working I don't know why here's my code below if I'm missing anything please tell me.
My code
findViewById(R.id.img_hint).setOnClickListener(e -> {
TooltipWindow tipWindow = new TooltipWindow(SelectAnAmount.this);
View toolTipView = getLayoutInflater().inflate(R.layout.tooltip_layout, null, false);
TextView textView = toolTipView.findViewById(R.id.text_title);
textView.setText("test");
int screen_pos[] = new int[2];
findViewById(R.id.img_hint).getLocationOnScreen(screen_pos);
if (!tipWindow.isTooltipShown()) {
tipWindow.showToolTip(toolTipView, screen_pos);
} else {
tipWindow.dismissTooltip();
}
});
And here's the method that I'm using to show the tooltip
public void showToolTip(View anchor,int[]screen_pos) {
tipWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
tipWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
tipWindow.setOutsideTouchable(true);
tipWindow.setTouchable(true);
tipWindow.setFocusable(true);
tipWindow.setBackgroundDrawable(new BitmapDrawable());
tipWindow.setContentView(contentView);
// Get rect for anchor view
Rect anchor_rect = new Rect(screen_pos[0], screen_pos[1], screen_pos[0]
+ anchor.getWidth(), screen_pos[1]-500 + anchor.getHeight());
// Call view measure to calculate how big your view should be.
contentView.measure(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int contentViewHeight = contentView.getMeasuredHeight();
int contentViewWidth = contentView.getMeasuredWidth();
// In this case , i dont need much calculation for x and y position of
// tooltip
// For cases if anchor is near screen border, you need to take care of
// direction as well
// to show left, right, above or below of anchor view
int position_x = anchor_rect.centerX() - (contentViewWidth / 2);
int position_y = anchor_rect.bottom - (anchor_rect.height() / 2);
tipWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, position_x, position_y);
// send message to handler to dismiss tipWindow after X milliseconds
// handler.sendEmptyMessageDelayed(MSG_DISMISS_TOOLTIP, 4000000);
}
tooltip layot
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/dialog_tooltip"
android:orientation="vertical">
<TextView
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/poppins_semibold"
android:text="Tooltip Title"
android:textColor="#color/white"
android:textSize="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_title"
android:fontFamily="#font/poppins"
android:text="An example of the text that\n will be displayed in\n this tooltip"
android:textColor="#color/white"
android:textSize="12dp" />
</LinearLayout>
<TextView
android:layout_width="20dp"
android:layout_height="80dp"/>
</LinearLayout>
my layout output img

View.Gone inside adapter leaves space in onBindViewHolder

This is my onBindViewHolder method:
#Override
public void onBindViewHolder(#NonNull final mViewHolder h, int i) {
final JSON data = jdata[i];
if(data .getName() != null && data .getStatus() !=null) {
h.textcontainer.setVisibility(View.VISIBLE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ ViewGroup.LayoutParams.WRAP_CONTENT,
/*weight*/ 1.0f
);
h.textcontainer.setLayoutParams(params);
h.title.setText(feed.getName());
} else {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ ViewGroup.LayoutParams.WRAP_CONTENT,
/*weight*/ 2
);
h.textcontainer.setVisibility(View.GONE);
h.playerView.setLayoutParams(params);
}
and this my XML:
<LinearLayout
android:id="#+id/videopost_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical"
android:weightSum="2"
>
<LinearLayout
android:id="#+id/video_textcontainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="#dimen/feed_item_padding_left_right"
android:paddingRight="#dimen/feed_item_padding_left_right"
android:paddingBottom="#dimen/feed_item_padding_top_bottom"
android:paddingTop="#dimen/feed_item_padding_top_bottom"
android:layout_weight="1"
>
<TextView
android:id="#+id/video_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold"
android:textColor="#color/background"
android:paddingStart="#dimen/feed_item_profile_info_padd"
android:paddingEnd="#dimen/feed_item_profile_info_padd"
/>
</LinearLayout>
<com.google.android.exoplayer2.ui.PlayerView
android:id="#+id/exo_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:show_buffering="true"
android:layout_weight="1"
>
</com.google.android.exoplayer2.ui.PlayerView>
My Adapter has a textview in it, when the json data = null, I obviously want to hide that TextView without any spacing left, and when the data (title for the video) isn't null, I want to show the text.
The current codes hides the TextView, but leaves an empty space. If I delete the following two lines from the if-statemant:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ ViewGroup.LayoutParams.WRAP_CONTENT,
/*weight*/ 1.0f
);
h.textcontainer.setLayoutParams(params);
Then there's no empty space left, but the TextView won't display if the data isn't empty. I'm pretty sure this is some stupid error somewhere, but I'm not able to find it. SOS :-)
Firstly, you have two individual layouts LinearLayout and PlayerView sharing a weight sum of two (2) making it a 50:50 distribution. Whether the child view of the LinearLayout is gone the 50% space would still remain until it's given out.
Hence any time you need to hide textview/title completely and remove not-needed space, dynamically set the weight of PlayerView to two (2) and make the visibility of LinearLayout gone.
The LinearLayout around your TextView is redundant. You can simplify this to simply be a single LinearLayout with two children. Set the height to wrap_content and do not specify a weightSum. When the TextView's visibility is set to GONE, PlayerView will be the only visible child and your LinearLayout will match its size.
<LinearLayout
android:id="#+id/videopost_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical">
<TextView
android:id="#+id/video_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold"
android:textColor="#color/background"
android:paddingStart="#dimen/feed_item_profile_info_padd"
android:paddingEnd="#dimen/feed_item_profile_info_padd"
/>
<com.google.android.exoplayer2.ui.PlayerView
android:id="#+id/exo_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:show_buffering="true"/>
</LinearLayout>

How to create a scroll list of custom relative layouts not stacking upon each other in Android Studio?

I want to create a scroll view list which would show "boxes" or more accurately custom made layouts (I'm using a custom class that extends a RelativeLayout - basically shows different pieces of information, some are static like places' working hours and some change dynamically and will be pulled from a server).
Though I encountered a problem - I (for the sake of seeing if my solution works) created 5 boxes and added them to the scroll view list but it seems like they are stacked upon each other. What's the proper way to make them appear one under another without manually tweaking their position coordinates? I was using addView() for that purpose but it doesn't work as intended for me or I use it poorly. If you know the answer, please briefly describe how this should be done.
Thanks in advance!
EDIT, here goes the code:
public class RestaurantBox extends RelativeLayout {
RestaurantBox (Context context){
super(context);
this.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
TextView restaurantName = new TextView(context);
restaurantName.setText("Test Restaurant");
RelativeLayout.LayoutParams restNameParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
this.addView(restaurantName, restNameParams);
restaurantName.setTypeface(null, Typeface.BOLD);
TextView freeSpots = new TextView(context);
freeSpots.setText("15/20");
RelativeLayout.LayoutParams freeSpotParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
freeSpotParams.topMargin = restNameParams.bottomMargin + 50;
this.addView(freeSpots, freeSpotParams);
TextView book = new TextView(this.getContext());
RelativeLayout.LayoutParams bookParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
book.setText("Book");
bookParams.setMargins(0,freeSpotParams.bottomMargin + 100,0,0);
this.addView(book, bookParams);
}
}
public class BrowseRestaurants extends AppCompatActivity {
int restaurantCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_restaurants);
Intent intent = getIntent();
String login = intent.getStringExtra("LOGIN");
TextView text = (TextView) findViewById(R.id.txtWelcomeUser);
text.setText("Welcome, " + login);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relLayoutRestaurants);
RestaurantBox initRBox = new RestaurantBox(this);
initRBox.setTop(0);
initRBox.setBottom(300);
relativeLayout.addView(initRBox);
for(int i=1;i<5;i++){
final View view = relativeLayout.getChildAt(i-1);
RestaurantBox restaurantBox = new RestaurantBox(this);
restaurantBox.setTop(view.getBottom() + 50);
restaurantBox.setBottom(restaurantBox.getTop() + 300);
relativeLayout.addView(restaurantBox);
}
}
}
<!-- activity_browse_restaurants.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"
android:fillViewport="true"
android:orientation="vertical"
tools:context="com.konrad.rezerwacje1.BrowseRestaurants">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewRestaurants"
android:layout_below="#+id/txtWelcomeUser"
android:layout_alignParentStart="true">
<RelativeLayout
android:id="#+id/relLayoutRestaurants"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="65dp"
android:orientation="vertical">
</RelativeLayout>
</ScrollView>
<TextView
android:id="#+id/txtLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Logout"
android:textColor="#android:color/holo_red_dark"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/txtWelcomeUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#android:color/holo_blue_dark"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp" />
</RelativeLayout
>
you are adding view in RelativeLayout so view stacking on each other so change it to LinearLayout in activity_browse_restaurants.xml
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewRestaurants"
android:layout_below="#+id/txtWelcomeUser"
android:layout_alignParentStart="true">
<LinearLayout
android:id="#+id/relLayoutRestaurants"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="65dp"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
now make changes according to in BrowseRestaurants.class
replace
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relLayoutRestaurants);
with
LinearLayout relativeLayout = (LinearLayout) findViewById(R.id.relLayoutRestaurants);
else will be fine if you want to change variable name its up to u, let me know if any problem

Changing height of ListView spoils alignment

I have a fragment inside a ViewPager and am trying to dynamically change the height of a ListView depending on the size of the screen.
Here is the xml code for my fragment:
Fragment.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RelativeLayout
android:id="#+id/rlDiscoveredDevice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvSuggestBTOn">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvDiscoveredDevices"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:text="#string/text_list_discovered_devices"
/>
<ProgressBar
android:id="#+id/pbDiscoveredDevices"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/tvDiscoveredDevices"
android:layout_marginStart="16dp"
/>
<ListView
android:id="#+id/lstDiscoveredBTDevices"
android:layout_height="250dp"
android:layout_width="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvDiscoveredDevices"
android:layout_marginTop="#dimen/list_view_margin_top"
/>
</RelativeLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pairBT"
android:background="#drawable/ic_action_down"
android:layout_marginStart="134dp"
android:layout_below="#+id/rlDiscoveredDevice"
android:layout_alignParentStart="true"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/unpairBT"
android:background="#drawable/ic_action_up"
android:layout_below="#+id/rlDiscoveredDevice"
android:layout_toEndOf="#+id/pairBT"
android:layout_marginStart="73dp"
/>
<RelativeLayout
android:id="#+id/rlPairedDevice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/pairBT">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPairedDevices"
android:text="#string/text_list_paired_devices"
android:layout_alignParentStart="true"
/>
<ListView
android:id="#+id/lstPairedBTDevices"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvPairedDevices"
android:layout_alignParentStart="true"
android:layout_marginTop="#dimen/list_view_margin_top"
/>
</RelativeLayout>
</RelativeLayout>
Here is my java code that I use to dynamically change the height:
DiscoveredDevice.java
public class DiscoveredDevice extends Fragment{
final String TAG = "DiscoverDevice Fragment";
private SharedPreferences appPrefs;
private BTActions btActions;
private ArrayList<BluetoothDevice> arrDiscoveredDevicesList;
private Set<BluetoothDevice> arrPairedDevicesList;
private ArrayAdapter<String> btDiscListArrayAdapter;
private ArrayAdapter<String> btPairedListArrayAdapter;
private String strDiscoveredListItemSelected = "";
private String strPairedListItemSelected = "";
private CommonFunctions cf;
private boolean blnIsFragmentLoaded = false;
// UI Objects
private TextView tvDiscoveredDevices;
private TextView tvPairedDevices;
private ListView lvDiscoveredList;
private ListView lvPairedDevicesList;
private ImageButton ibtnPair;
private ImageButton ibtnUnPair;
private ProgressBar pbDiscDevicesSpinner;
private TextView tvSuggestBTOn;
private ProgressBar pbLoading;
public DiscoveredDevice() {
btActions = new BTActions();
cf = new CommonFunctions();
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Begin render of Discovered Device fragment...");
super.onCreate(savedInstanceState);
// Define variables
appPrefs = this.getActivity().getPreferences(Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_discovered_device, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Define the lists on DiscoveredDevice fragment
btDiscListArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.simple_row, R.id.simple_row_Txt);
btPairedListArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.simple_row, R.id.simple_row_Txt);
// Define UI Objects
defineUIObjects();
// Position UI objects
positionUIObjects();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
private void defineUIObjects() {
tvDiscoveredDevices = (TextView) getView().findViewById(R.id.tvDiscoveredDevices);
tvPairedDevices = (TextView) getView().findViewById(R.id.tvPairedDevices);
lvDiscoveredList = (ListView) getView().findViewById(R.id.lstDiscoveredBTDevices);
lvPairedDevicesList = (ListView) getView().findViewById(R.id.lstPairedBTDevices);
ibtnPair = (ImageButton) getView().findViewById(R.id.pairBT);
ibtnUnPair = (ImageButton) getView().findViewById(R.id.unpairBT);
tvSuggestBTOn = (TextView) getView().findViewById(R.id.tvSuggestBTOn);
pbDiscDevicesSpinner = (ProgressBar) getView().findViewById(R.id.pbDiscoveredDevices);
pbLoading = (ProgressBar) getView().findViewById(R.id.spin_kit_progress);
pbLoading.setIndeterminateDrawable(new DoubleBounce());
}
private void positionUIObjects() {
final ViewGroup vgDiscDevice = (ViewGroup) getView().findViewById(R.id.rlDiscoveredDevice);
final AtomicInteger aiLayoutHeight = new AtomicInteger();
Rect rect = new Rect();
// Get the window
Window win = getActivity().getWindow();
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Find height of AppBarLayout
AppBarLayout ablTabs = (AppBarLayout) getActivity().findViewById(R.id.ablTabs);
// Obtain the screen height & width
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int intScreenHeight = metrics.heightPixels;
int intScreenWidth = metrics.widthPixels;
Log.i(TAG, "Actual Screen Height = " + intScreenHeight + " Width = " + intScreenWidth);
// Set the height for Discovered Devices list
RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) getView().findViewById(R.id.rlDiscoveredDevice).getLayoutParams();
// Get height of Discovered Devices relative layout
int intDiscoveredDevicesRLHeight = (int)(Math.round((intScreenHeight - rect.top - ablTabs.getMeasuredHeight()) * 0.45));
Log.i(TAG, "Setting the height of Discovered Devices Relative layout as '" + intDiscoveredDevicesRLHeight + "'");
rlParams.topMargin = ablTabs.getMeasuredHeight();
rlParams.leftMargin = 50; // I DID THIS JUST TO CHECK IF THE LEFT MARGIN GETS MOVED TO THE RIGHT. THIS IS WHERE I NEED A BETTER WAY TO PROPERLY ALIGN THE LIST
rlParams.height = intDiscoveredDevicesRLHeight;
lvDiscoveredList.setLayoutParams(rlParams);
}
I want each list to occupy 45% of the screen(excluding the AppBarLayout). If you see the below screenshot, when I set the new height, the ListView goes out of alignment and part of it gets cuts to the left of the screen. I have set the Left margin to 50 to bring it into view.
[Screenshot]
I have placed 2 ListViews inside a RelativeLayouts so that they can be individually controlled as a whole. Am I doing something wrong here ?
I think you can achieve this with just xml, no dynamic resizing!
In your post you mentioned that you want the list views to each take 45% of the available height. Thus, I am assuming that the center content with the image views will take 10% of the height (though this approach will also work if they had a fixed height, I'll include that answer too at the bottom.
All you need to do is change your top level layout to a LinearLayout (with a vertical orientation), put your image views inside of a LinearLayout (with horizontal orientation), change some of the heights of your views and add layout_weight attributes to the two RelativeLayouts and the inner LinearLayout you will create. Here is an example of what your xml will look like:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<RelativeLayout
android:id="#+id/rlDiscoveredDevice"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="#+id/tvSuggestBTOn"
android:layout_weight="9">
<TextView
android:id="#+id/tvDiscoveredDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="#string/text_list_discovered_devices"
/>
<ProgressBar
android:id="#+id/pbDiscoveredDevices"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/tvDiscoveredDevices"
/>
<ListView
android:id="#+id/lstDiscoveredBTDevices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tvDiscoveredDevices"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:background="#drawable/abc_list_selector_disabled_holo_dark"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="center"
android:layout_weight="2">
<ImageButton
android:id="#+id/pairBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_down"
/>
<ImageButton
android:id="#+id/unpairBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_up"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rlPairedDevice"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPairedDevices"
android:text="#string/text_list_paired_devices"
android:layout_alignParentStart="true"
/>
<ListView
android:id="#+id/lstPairedBTDevices"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="#dimen/list_view_divider_height"
android:choiceMode="singleChoice"
android:listSelector="#color/list_item_selected"
android:layout_below="#+id/tvPairedDevices"
android:layout_alignParentStart="true"
android:background="#drawable/abc_list_selector_disabled_holo_dark"
/>
</RelativeLayout>
</LinearLayout>
The important thing to note here is that the RelativeLayouts now have a weight of 9 each and the center linear layout has a weight of 2. Thus the space in the top level linear layout will be divided in that ratio, the RelativeLayouts will get 45% each and the LinearLayout will get 10%.
If you wanted the linear layout in the center to be wrap content instead of taking 10% of the screen (I would recommend this) then you could go ahead and assign it a height of wrap_content and remove the layout_weight attribute from it. The top level LinearLayout will then take the leftover height after allocating space for the center LinearLayout and divide it evenly between the two Relative layouts.
PS: (Heads up, you can probably use the xml I posted here. I set backgrounds on the list views to make it easy for me to see their sizes without data, make sure to remove those).
PPS: Note that this approach allows you to remove a lot of the layout positioning attributes that you had with a top level relative layout! This not only improves the cleanliness of your code, but also makes your UI more performant (Relative Layouts are less performant than other view groups, especially when nested).

ImageView inside ListView is ignoring all layout dimensions and filling the whole screen

I'm trying to create a set of 4 dynamically updating listviews of icons.
To do this, I've put my 4 listviews inside a gridview, and I'm using a custom layout for each listview item with a single imageview inside it. I'm handling changing the icon inside a custom adapter. I'm using the Picasso library to handle the icons, and all my icons are stored locally in drawable as .png files.
I'm not getting any errors, but when I run the app, all I get is a single icon that takes up the whole screen. I have a small imageview and a textview above the gridview that contains the lists of icons, but the one icon pushes even that out of the way.
This is my layout preview, and a screenshot of the app running in an emulator. (the result is the same if I run on my phone).
preview,
running
(apologies for not embedding, I'm new to SO, and don't have 10 rep yet haha)
I've tried resizing the image at runtime inside my custom adapter. I've tried setting the maximum width of the listview - both at runtime (since I want to adapt to different screen dimensions), and in the xml files. I've tried resizing the source .png files outside of android studio. Nothing's worked.
My activity xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sta.tomov0.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tomoFace"
android:src="#drawable/office38"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:layout_below="#+id/tomoFace"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="false"
android:layout_marginBottom="50dp" />
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:rowCount="1"
android:id="#+id/gridLayout"
android:layout_below="#+id/textView"
android:columnCount="5">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewA"
android:layout_row="0"
android:layout_column="0" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewB"
android:layout_row="0"
android:layout_column="1" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewC"
android:layout_row="0"
android:layout_column="2" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewD"
android:layout_column="3"
android:layout_row="0" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:layout_column="4"
android:layout_row="0"
android:onClick="addTask"
android:src="#android:drawable/stat_notify_more" />
</GridLayout>
</RelativeLayout>
My listview layout:
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listImageView"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false" />
</RelativeLayout>
and my activity.java file:
public class MainActivity extends AppCompatActivity {
ImageView tomoface;
ListView listViewA;
ArrayList arrayListA = new ArrayList<Integer>();
Boolean aExists = false;
ListView listViewB;
ArrayList arrayListB = new ArrayList<Integer>();
Boolean bExists = false;
ListView listViewC;
ArrayList arrayListC = new ArrayList<Integer>();
Boolean cExists = false;
ListView listViewD;
ArrayList arrayListD = new ArrayList<Integer>();
Boolean dExists = false;
Button addButton;
TextView tomoText;
File tomoFiles;
File taskFiles;
String currentCommunity = "Dep";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paper.init(getApplicationContext());
tomoface = (ImageView) findViewById(R.id.tomoFace);
tomoface.setImageResource(R.drawable.favourite15);
tomoText = (TextView) findViewById(R.id.textView);
listViewA = (ListView) findViewById(R.id.listViewA);
listViewB = (ListView) findViewById(R.id.listViewB);
listViewC = (ListView) findViewById(R.id.listViewC);
listViewD = (ListView) findViewById(R.id.listViewD);
tomoFiles = getDir("TomoFiles", MODE_PRIVATE);
taskFiles = new File(tomoFiles, "taskFiles");
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width =(size.x)/5;
ViewGroup.LayoutParams params = listViewA.getLayoutParams();
params.height = width;
params.width = width;
listViewA.setLayoutParams(params);
listViewB.setLayoutParams(params);
listViewC.setLayoutParams(params);
listViewD.setLayoutParams(params);
/*
If there is no data saved, the following code creates a list of (empty) lists to hold TaskClass objects
The 4 sub lists each represent one category.
If there is data saved, the following code retrieves that data, and creates 4 new ArrayLists,
each containing the iconIds of the TaskClass objects in the corresponding position of the corresponding TaskClass arraylist.
These ArrayLists of ids are then used to populate the 4 listviews.
*/
ArrayList<ArrayList<TaskClass>> listList = Paper.book(currentCommunity).read("listList", new ArrayList<ArrayList<TaskClass>>());
if (listList.size() == 0){
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
} else {
for(TaskClass t:listList.get(0)){
arrayListA.add(t.getIcon());
}
for(TaskClass t:listList.get(1)){
arrayListB.add(t.getIcon());
}
for(TaskClass t:listList.get(2)){
arrayListC.add(t.getIcon());
}
for(TaskClass t:listList.get(3)){
arrayListD.add(t.getIcon());
}
}
Integer[] intArrayA = new Integer[arrayListA.size()];
for (int i = 0; i < arrayListA.size(); i++){
intArrayA[i] =(Integer) arrayListA.get(i);
}
ArrayAdapter adapterA = new CustomArrayAdapter(getApplicationContext(),intArrayA);
listViewA.setAdapter(adapterA);
Integer[] intArrayB = new Integer[arrayListB.size()];
for (int i = 0; i < arrayListB.size(); i++){
intArrayB[i] =(Integer) arrayListB.get(i);
}
ArrayAdapter adapterB = new CustomArrayAdapter(getApplicationContext(),intArrayB);
listViewB.setAdapter(adapterB);
Integer[] intArrayC = new Integer[arrayListC.size()];
for (int i = 0; i < arrayListC.size(); i++){
intArrayC[i] =(Integer) arrayListC.get(i);
}
ArrayAdapter adapterC = new CustomArrayAdapter(getApplicationContext(),intArrayC);
listViewC.setAdapter(adapterC);
Integer[] intArrayD = new Integer[arrayListD.size()];
for (int i = 0; i < arrayListD.size(); i++){
intArrayD[i] =(Integer) arrayListD.get(i);
}
ArrayAdapter adapterD = new CustomArrayAdapter(getApplicationContext(),intArrayD);
listViewD.setAdapter(adapterD);
}
//TODO: create a custom adapter that will display icons correctly
public class CustomArrayAdapter extends ArrayAdapter{
private final Context context;
private final Integer[] values;
public CustomArrayAdapter(Context context, Integer[] values) {
super(context, -1, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View iconView = inflater.inflate(R.layout.iconlayout, parent, false);
ImageView imageView = (ImageView) iconView.findViewById(R.id.listImageView);
int s =(int) values[position];
imageView.setImageResource(s);
//get the device width, to calculate icon width, and then set icon width accordingly
//TODO: setting icon width not working
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width =(size.x)/5;
Uri uri = Uri.parse("android.resource://com.example.sta.tomov0/drawable/"+s);
Picasso.with(context).load(uri).resize(width,width).fit().centerCrop().into(imageView);
return iconView;
}
}
}
A note: I have a custom data management class that returns arraylists. That's tested separately and working fine. The arraylists that are being fed to the adapter are int arraylists of the drawable references.
Help! What am I doing wrong? I've been searching through SO all day and trying different things. The solutions posted in these questions haven't helped T-T:
How to set ImageView width in android ListView?
ImageView in ListView that expands maximum width
(that was a bit difficult to implement, and just created other problems - it seems like overkill to create a custom view class just for displaying an icon?)
Give fixed height to your Imageview in My listview layout:
Say Something like
<?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="wrap_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="120dp"
android:id="#+id/listImageView"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false" />
</RelativeLayout>
I'm assuming #drawable/office38 is the image shown in your screenshot (taking up the whole screen)?
Try setting the dimensions of this image to something small, eg:
android:layout_width="50dp"
android:layout_height="50dp"
I know this may not be what you are actually looking to do, but at least it will show you if the problem is with that first ImageView or not and will free up space below it for the TextView and the GridLayout. It could be that the drawable is massive, and as you aren't specifying a set width/height or any scale options, it takes up all the space it can.
Also, have a look at http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType which describes the different scaling options you have with an ImageView.
GOT IT.
sorry guys. It was a really dumb problem after all.
My listview adapter is working fine it turns out. The problem was in the imageview that was outside of the lists (tomoface) - for some reason, I decided to set it to a different drawable on runtime, and hadn't scaled that at all haha.

Categories