I've a problem about remove CardView in layout I need to remove perfectly clear 100% not hide something like setvisibility(View.GONE) Please save my day Thanks.
this my code in layout
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="130dp">
<RelativeLayout
android:id="#+id/relative1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal">
<TextView
android:id="#+id/textView_header1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:text="Weather"
android:textColor="#color/colorWhite"
android:textSize="15sp" />
<!--<android.support.v7.widget.CardView--> this is simple cardview
<!--android:id="#+id/card_view_1_1"-->
<!--android:layout_width="270dp"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_below="#+id/textView_header1"-->
<!--android:layout_gravity="center"-->
<!--android:layout_marginLeft="15dp"-->
<!--android:layout_marginRight="15dp"-->
<!--app:cardBackgroundColor="#color/colorWhite"-->
<!--app:cardCornerRadius="4dp">-->
</RelativeLayout>
</HorizontalScrollView>
This is how i create card
enter code here
public void createCard(String hum_val, String temp_val) {
int humidValTextSize = 35;
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
humidValTextSize = 35;
} else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
humidValTextSize = 17;
}
/*
------Structure of item------
CardView
|__RelativeLayout (inside CardView)
|___ImageView
|___TextView
|___TextView
*/
// Relative Layout inside CardView ---
RelativeLayout layout_in_card = new RelativeLayout(getActivity());
layout_in_card.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
layout_in_card.setPadding(15, 15, 15, 15);
layout_in_card.setMinimumWidth(300);
// End initialize RelativeLayout_Inside_CardView
// ImageView inside Relative Layout ---
ImageView imageView1 = new ImageView(getActivity());
RelativeLayout.LayoutParams layoutImg = new RelativeLayout.LayoutParams(80, 80);
layoutImg.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutImg.addRule(RelativeLayout.ALIGN_PARENT_TOP);
layoutImg.setMargins(0, 0, 16, 0);
imageView1.setLayoutParams(layoutImg);
if (hum_val == null) {
imageView1.setImageResource(R.drawable.dashboard_nodata);
} else {
imageView1.setImageResource(R.drawable.dashboard_humidicon);
}
imageView1.setId(Integer.parseInt(currentImageViewId.toString()));
currentImageViewId++;
layout_in_card.addView(imageView1);
// End initialize ImageView ---
// TextView inside Relative Layout ---
TextView txtViewName = new TextView(getActivity());
RelativeLayout.LayoutParams layoutTxtViewName = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layoutTxtViewName.addRule(RelativeLayout.ALIGN_PARENT_START);
layoutTxtViewName.addRule(RelativeLayout.BELOW, imageView1.getId());
layoutTxtViewName.setMargins(0, 20, 0, 0);
txtViewName.setText("Humidity");
//txtViewName.setText("Humidity");
txtViewName.setTextSize(humidValTextSize);
txtViewName.setLayoutParams(layoutTxtViewName);
layout_in_card.addView(txtViewName);
// End initialize TextView ---
// TextView inside Relative Layout ---
TextView txtViewValue = new TextView(getActivity());
RelativeLayout.LayoutParams layoutTxtViewValue = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layoutTxtViewValue.addRule(RelativeLayout.ALIGN_BASELINE, imageView1.getId());
layoutTxtViewValue.addRule(RelativeLayout.ALIGN_BOTTOM, imageView1.getId());
layoutTxtViewValue.addRule(RelativeLayout.ALIGN_PARENT_END);
layoutTxtViewValue.setMargins(1, 0, 0, 0);
layoutTxtViewValue.addRule(RelativeLayout.TEXT_ALIGNMENT_GRAVITY, RelativeLayout.CENTER_VERTICAL);
if (hum_val == null) {
txtViewValue.setText("N/A");
} else {
txtViewValue.setText(hum_val + "%");
}
txtViewValue.setTextSize(humidValTextSize);
txtViewValue.setLayoutParams(layoutTxtViewValue);
layout_in_card.addView(txtViewValue);
// End initialize TextView ---
// CardView Root
CardView cardView = new CardView(getActivity());
cardView.setId(Integer.parseInt(currentCardViewId.toString()));
currentCardViewId++;
if (currentRefCardViewId == null) {
// currentRefCardViewId = R.id.card_view_1_2;
}
RelativeLayout.LayoutParams layoutCardView = new RelativeLayout.LayoutParams(270, RelativeLayout.LayoutParams.MATCH_PARENT);
layoutCardView.addRule(RelativeLayout.BELOW, R.id.textView_header1);
layoutCardView.addRule(RelativeLayout.TEXT_ALIGNMENT_GRAVITY, RelativeLayout.CENTER_VERTICAL);
if (currentRefCardViewId != null) {
layoutCardView.addRule(RelativeLayout.RIGHT_OF, currentRefCardViewId);
}
currentRefCardViewId = cardView.getId();
layoutCardView.setMargins(15, 0, 15, 0);
cardView.setLayoutParams(layoutCardView);
cardView.setRadius(4);
cardView.setCardBackgroundColor(ColorStateList.valueOf(Color.WHITE));
cardView.setPadding(15, 0, 15, 0);
cardView.addView(layout_in_card);
RelativeLayout relativeLayout = (RelativeLayout) getView().findViewById(R.id.relative1);
relativeLayout.addView(cardView);
createCard_temp(temp_val);
}
Related
In a Table Row, there is a horizontal scroll view containing a Linear Layout,
The intention is to place 5 Imageview's inside the Linear Layout dynamically
The problem is it seems the Imageview's are shifted and the Linear Layout does not fill the horizontal scroll view
Here is the xml:
<TableRow
android:id="#+id/table_3_Row_7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0.1mm"
android:background="#color/color21"
android:gravity="center"
>
<HorizontalScrollView
android:layout_span="3"
android:id="#+id/table_3_Row_7_HSV1"
android:background="#FFFFFF"
android:focusableInTouchMode="true"
android:focusable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="horizontal"
android:fadeScrollbars="false"
android:scrollbarSize="0.5mm"
android:scrollbarThumbHorizontal="#color/colorDevider"
>
<LinearLayout
android:id="#+id/table_3_Row_7_HSV1LL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/color02"
android:layout_gravity="center"
>
</LinearLayout>
</HorizontalScrollView>
<LinearLayout
android:id="#+id/table_3_Row_7_ImageView1"
android:layout_span="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/color21"
>
</LinearLayout>
</TableRow>
The mentioned Liniear Layout is table_3_Row_7_HSV1LL
And the code is as following:
int mMaxCount = 5;
ImageView[]mImageView = new ImageView[mMaxCount];
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//params1.setMargins(10, 75, 0, 0);
params1.setMargins(100, 0, 0, 0);
params1.height = 200;
params1.width = 200;
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//params2.setMargins(100, 85+20, 0, 0);
params2.setMargins(100, 0, 0, 0);
params2.height = 170;
params2.width = 170;
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//params3.setMargins(100, 95+20, 0, 0);
params3.setMargins(100, 0, 0, 0);
params3.height = 140;
params3.width = 140;
LinearLayout.LayoutParams params4 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//params4.setMargins(100, 105+20, 0, 0);
params4.setMargins(100, 0, 0, 0);
params4.height = 110;
params4.width = 110;
LinearLayout.LayoutParams params5 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//params5.setMargins(100, 115+20, 0, 0);
params5.setMargins(100, 0, 0, 0);
params5.height = 80;
params5.width = 80;
params5.gravity = Gravity.CENTER;
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().setGravity(Gravity.CENTER);
for (int i = 0; i < mMaxCount; i++)
{
mImageView[i] = new ImageView(mContext);
//mImageView[i].setBackgroundColor(Color.TRANSPARENT);
mImageView[i].setTag("T"+"I"+i);
mImageView[i].setId(i);
mImageView[i].setFocusable(true);
mImageView[i].setClickable(true);
if (i == 0)
{
//Picasso.with(mContext).load(R.drawable.size1).placeholder(R.drawable.ic_launcher).resize(200, 200).into(mImageView[i]);
mImageView[i].setBackgroundResource(R.drawable.size1);
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().addView(mImageView[i], params1);
}
else if (i == 1)
{
//Picasso.with(mContext).load(R.drawable.size1).placeholder(R.drawable.ic_launcher).resize(170, 170).into(mImageView[i]);
mImageView[i].setBackgroundResource(R.drawable.size1);
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().addView(mImageView[i], params2);
}
else if (i == 2)
{
//Picasso.with(mContext).load(R.drawable.size1).placeholder(R.drawable.ic_launcher).resize(140, 140).into(mImageView[i]);
mImageView[i].setBackgroundResource(R.drawable.size1);
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().addView(mImageView[i], params3);
}
else if (i == 3)
{
//Picasso.with(mContext).load(R.drawable.size1).placeholder(R.drawable.ic_launcher).resize(110, 110).into(mImageView[i]);
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().addView(mImageView[i], params4);
}
else if (i == 4)
{
//Picasso.with(mContext).load(R.drawable.size1).placeholder(R.drawable.ic_launcher).resize(80, 80).into(mImageView[i]);
mImageView[i].setBackgroundResource(R.drawable.size1);
mLayoutStruct.getLayout_table_3_Row_7_HSV1LL().addView(mImageView[i], params5);
}
}
The background color of horizontal scroll view is White
The background color of the Linear Layout is Red
I expect the Red color continues till the end of White color and covers it
Another point is when horizontally scrolling, I just see 4 Imageview's instead of 5
First of All:
Its Better to Use RecylerView to Add Items to a list. this example may help you.
RecylerView is Backward compatible so it runs on older version that api 22 you dont need to set minSDK to 22.
Your Solution for Adding item to Linearlayout should be better. you can make array of your params to avoid if/else inside loop.
Answer:
You See 4 ImageView because You Forget To Add
mImageView[i].setBackgroundResource(R.drawable.size1);
inside your else if (i == 3) So it adds imageview with empty Background that is not visible.
And
for covering all the WHITE color of your horizontal scroll view by RED you have to set android:fillViewport="true" on the HorizentalScrollView like below:
<HorizontalScrollView
android:id="#+id/table_3_Row_7_HSV1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:layout_span="3"
android:background="#FFFFFF"
android:fadeScrollbars="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollbarSize="0.5mm"
android:scrollbarThumbHorizontal="#color/gray"
android:scrollbars="horizontal">
I solved the issue by
1 - Deleting android:layout_gravity="center" from the LinearLayout
2 - Utilizing setPadding to the horizontal scroll view to shift it down to the center of the table row
For the below point you need to change the code as shown below.
"Another point is when horizontally scrolling, I just see 4 Imageview's instead of 5"
for (int i = 0; i < mMaxCount; i++)
to
for (int i = 0; i <=mMaxCount; i++)
I am trying to create a stack of cards dynamically by using a RelativeLayout and setting the ALIGN_PARENT_BOTTOM rule and the bottomMargin. But the cards keep getting drawn over each other disregarding the margin. But they draw properly when I use ALIGN_PARENT_TOP and topMargin.
activity_single_player_game.xml (Code creating RelativeLayout)
<!-- other code -->
<RelativeLayout
android:id="#+id/frame_card_stack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="bottom" >
<ImageView
android:id="#+id/image_hand_value"
android:layout_width="40dip"
android:layout_height="20dip"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dip" />
<TextView
android:id="#+id/text_hand_value"
android:layout_width="40dip"
android:layout_height="20dip"
android:gravity="center"
android:layout_alignParentBottom="true"
android:background="#88000000" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/frame_card_stack_split"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:gravity="bottom" >
<ImageView
android:id="#+id/image_hand_value_split"
android:layout_width="40dip"
android:layout_height="20dip"
android:layout_alignParentBottom="true" />
<TextView
android:id="#+id/text_hand_value_split"
android:layout_width="40dip"
android:layout_height="20dip"
android:gravity="center"
android:layout_alignParentBottom="true"
android:background="#88000000" />
</RelativeLayout>
<!-- other code -->
SinglePlayerGameActivity.java (Code creating the stack of cards)
RelativeLayout playerView;
RelativeLayout playerViewSplit;
#Override
protected void OnCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_player_game);
playerView = (RelativeLayout) findViewById(R.id.frame_card_stack);
playerViewSplit = (RelativeLayout) findViewById(R.id.frame_card_stack_split);
}
public ImageView getCardImage(BJCard card, int offset, boolean playerCard) {
ImageView cardImage = new ImageView(this);
cardImage.setImageResource(BJUtility.drawableIdForCard(card));
cardImage.setBackgroundColor(0x40000000);
if (playerCard) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = dip(20 * offset);
cardImage.setLayoutParams(params);
} else {
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
cardImage.setLayoutParams(params);
}
return cardImage;
}
public void populatePlayer() {
BJPlayerBox box = MenuActivity.bjmc.playerBoxes.get(MenuActivity.bjmc.activePlayerBox);
BJCardDeck deck = box.cardDecks.get(box.activeDeckIndex);
for (int i = 0; i < deck.cards.size(); i++) {
BJCard card = deck.cards.get(i);
playerView.addView(getCardImage(card, i, true), playerView.getChildCount() - 2);
}
updatePlayerSumView(deck, BEGIN, box.activeDeckIndex);
}
public void updatePlayer(int flag) {
BJPlayerBox box = MenuActivity.bjmc.playerBoxes.get(MenuActivity.bjmc.activePlayerBox);
switch (flag) {
case HIT:
BJCardDeck deck = box.cardDecks.get(box.activeDeckIndex);
for (int i = playerView.getChildCount() - 2; i < deck.cards.size(); i++) {
BJCard card = deck.cards.get(i);
playerView.addView(getCardImage(card, i, true), playerView.getChildCount() - 2);
}
updatePlayerSumView(deck, flag, box.activeDeckIndex);
break;
case SPLIT:
playerViewSplit.setVisibility(android.view.View.VISIBLE);
ImageView splitCardView = (ImageView) playerView.getChildAt(playerView.getChildCount() - 2);
playerView.removeView(splitCardView);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.bottomMargin = dip(0);
playerViewSplit.addView(splitCardView, playerViewSplit.getChildCount() - 2);
splitCardView.setLayoutParams(params);
// update first deck
BJCardDeck splitDeck = box.cardDecks.get(0);
BJCard card = splitDeck.cards.get(1);
playerView.addView(getCardImage(card, 1, true), playerView.getChildCount() - 2);
updatePlayerSumView(splitDeck, SPLIT, 0);
// update split deck
splitDeck = box.cardDecks.get(1);
card = splitDeck.cards.get(1);
playerViewSplit.addView(getCardImage(card, 1, true), playerViewSplit.getChildCount() - 2);
updatePlayerSumView(splitDeck, SPLIT, 1);
break;
case SURRENDER:
updatePlayerSumView(box.activeCardDeck(), flag, box.activeDeckIndex);
}
}
public void updatePlayerSumView(BJCardDeck deck, int flag, int splitIndex) {
ImageView iv;
TextView tv;
if (splitIndex == 0) {
iv = (ImageView) findViewById(R.id.image_hand_value);
tv = (TextView) findViewById(R.id.text_hand_value);
} else {
iv = (ImageView) findViewById(R.id.image_hand_value_split);
tv = (TextView) findViewById(R.id.text_hand_value_split);
}
if (flag == SURRENDER) {
tv.setText(null);
iv.setImageResource(R.drawable.flag);
return;
}
if (flag != SPLIT && BJUtility.isBlackjack(deck)) {
iv.setImageResource(R.drawable.crown);
} else {
int[] playerSum = BJUtility.currentCardHandTotal(deck.cards);
if (playerSum[0] > 21) {
tv.setText(null);
iv.setImageResource(R.drawable.bust);
} else {
if (playerSum.length == 1) {
tv.setText(Integer.toString(playerSum[0]));
tv.setTextColor(getResources().getColor(R.color.orangish_yellow));
} else {
// TODO: if deckState = active, show both, else, show one
tv.setText(playerSum[1] + "/" + playerSum[0]);
tv.setTextColor(getResources().getColor(R.color.orangish_yellow));
}
}
}
}
Here are some screenshots-
This is what I get when I use ALIGN_PARENT_TOP and topMargin. I want exactly this, except that the circled cards should be down with the text.
This is what I get when I use ALIGN_PARENT_BOTTOM and bottomMargin. Here the cards are in the correct position as a group, but they are all drawn completely over each other, so I can see only one.
What is your playerView??
If it is a RelativeLayout and the android:layout_height="wrap_content" then android:layout_marginBottom does not work.
Since setting android:paddingBottom="" to the playerView is not an option for you, you can try setting the android:layout_marginTop for the previous child views.
Something like, adding android:layout_marginTop to the 1st card, while adding the 2nd card.
I have written this piece of code. But it is not giving the proper result. Please let me know where is the mistake. And I don't want to use Linear Layout.
Here is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_relativeLayout1"
android:orientation="horizontal"
android:background="#ffffff">
</RelativeLayout>
</LinearLayout>
String[] but = {"Hello", "Bye"};
int buttonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customLayout = (RelativeLayout) findViewById(R.id.custom_relativeLayout1);
//customLayout is object of relativelayout.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (butArray[i].getId() != 1)
{
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
else
{
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
}
RelativeLayout.RIGHT_OFhoryzontally or vertically align?
so for vertically
Btnparams.addRule(RelativeLayout.BELOW, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
or for horizontally
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
instead of
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
LinearLayout is very nice to use if you want do dynamically add Views and scale them the same. For example if you want to add buttons and have max 3 buttons per row, you can also use another LinearLayout to make a new row.
I 'abuse' the LinearLayout row and a Button for layoutparams templating.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll_row1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
</LinearLayout>
Example code:
// Get LL and template params
LinearLayout root = (LinearLayout) findViewById(R.id.ll_root);
LinearLayout row1 = (LinearLayout) findViewById(R.id.ll_row1);
ViewGroup.LayoutParams llRowParams = row1.getLayoutParams();
ViewGroup.LayoutParams btnParams = findViewById(R.id.btn1).getLayoutParams();
// Make new button
Button newBtn = new Button(context);
newBtn.setLayoutParams(btnParams);
newBtn.setText("Button 3");
// Add button to row1
row1.addView(newBtn);
// Add new row
LinearLayout row2 = new LinearLayout(context);
row2.setLayoutParams(llRowParams);
root.addView(row2);
// TODO: add buttons to new row
// TODO: some logic to decide between adding to row or creating new row and adding button
Note: code is not tested, but you should get the idea.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.RIGHT_OF, i-1);
}
customLayout.addView(butArray[i], Btnparams);
}
I have an android activity which contains a horizontal list view. Below is the layout for it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id ="#+id/topMostLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grey">
<HorizontalScrollView
android:id ="#+id/horScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:id ="#+id/dateRibbon"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
>
</LinearLayout>
</HorizontalScrollView>
<TextView
android:id="#+id/line"
android:paddingTop="5dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background ="#37000000"
android:layout_below="#id/horScrollView"
/>
<LinearLayout
android:id="#+id/bottom_control_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_above="#id/bottom_control_bar"
android:layout_below="#id/line" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/bottom_control_bar"
android:layout_below="#id/horScrollView"
android:text="#string/tasks_empty" />
</RelativeLayout>
The problem is when I add views to the linearlayout inside the horizontalscrollview, it will not scroll fully to the right, so the rightmost child view is invisible to the user. I am adding textviews to the linearlayout. Below is the code for where the linear layout gets populated:
LinearLayout dateRibbon = FindViewById<LinearLayout>(Resource.Id.dateRibbon);
dateRibbon.RemoveAllViews();
TextView tView;
m_dateRibbonTextViews = new List<TextView>();
m_dateRibbonDates = new List<DateTime>();
int currentJobId = Telecetera.Connect.JobLibrary.JobData.Job.GetCurrentJobID();
int defaultCurrentJobID = Telecetera.Connect.JobLibrary.JobData.Job.SYSDIR_CURRENTJOB_DEFAULT;
Telecetera.Connect.JobLibrary.JobData.JobDetailsList jobDetailsList;
int i = -1;
foreach (DateTime date in jobsByDay.Keys)
{
++i;
jobDetailsList = jobsByDay[date];
tView = new TextView(this);
tView.Gravity = GravityFlags.CenterHorizontal;
tView.Text = GetDateDisplayString(date);
tView.SetTextSize(Android.Util.ComplexUnitType.Sp, 18);
tView.SetPadding(10, 0, 10, 0);
if (currentJobId != defaultCurrentJobID && jobDetailsList.GetByJobID(currentJobId) != null)
{
m_indicesDaysWithCurrentJob.Add(i);
tView.SetBackgroundColor(Android.Graphics.Color.Cyan);
}
else
{
tView.SetBackgroundColor(Android.Graphics.Color.White);
}
tView.Click += new EventHandler(tView_Click);
dateRibbon.AddView(tView);
m_dateRibbonTextViews.Add(tView);
m_dateRibbonDates.Add(date);
tView = new TextView(this);
tView.SetPadding(2, 0, 2, 0);
tView.SetBackgroundColor(Resources.GetColor(Resource.Color.grey));
dateRibbon.AddView(tView);
}
Any hints as to why it does not completely scroll to the right would be appreciated!
Thanks.
I was able to solve it by removing the
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
lines.
you can set padding to linear layout here's my code which show's the textview at center and give some space at start and at the end of view.
lLayTwo.setPadding((center - 2 - centerScreenChildLeft), 0, (center - 2 - centerScreenChildRight), 0);
private void addSubMenu(ArrayList<String> list,String mainMenu){
this.mainMenu = mainMenu;
lLayTwo.removeAllViews();
mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(mViewPlain));
menu = list;
Log.d(TAG, "meulist "+menu.size());
range = list.size() * 2 + 1;
Log.d(TAG, "range "+range);
int menuItem = 0;
for ( int i = 0; i < range; i++ ) {
if ( i % 2 == 0 ){
View txt = new View(MCSDistrictMainActivity.this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setBackgroundResource(R.drawable.line);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 3, 0, 0);
lLayTwo.addView(txt,params);
}else{
TextView txt = new TextView(MCSDistrictMainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(parentChildWidh, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 8, 0, 5);
params.gravity = Gravity.CENTER;
txt.setText(menu.get(menuItem));
txt.setTag(menu.get(menuItem));
txt.setTextColor(getResources().getColor(R.color.violet));
txt.setTextSize(15f);
txt.setGravity(Gravity.CENTER_HORIZONTAL);
menuItem += 1;
lLayTwo.addView(txt,params);
}
}
Log.d(TAG, "llayout Two "+lLayTwo.getChildCount()+" width "+parentChildWidh+" LEFT "+parentChildLeft);
int left = parentChildLeft;
int width = parentChildWidh;
int centerTab = 1 + hsvLowerTab.getWidth() / 2;
Log.d(TAG, "Measures left "+left+" width "+width+" center "+centerTab+" all "+( left + width -centerTab ));
//(left + width/2)-centerTab
hsvLowerTab.scrollTo((left + width/2)-centerTab, 0);
hsvLowerTab.dispatchTouchEvent (MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP,(left + width/2)-centerTab, 0, 0));
}
I try to add a TextView to a LinearLayout dynamically such as in the following code, but it doesn't appear when I run the application?
setContentView(R.layout.advanced);
m_vwJokeLayout=(LinearLayout) this.findViewById(R.id.m_vwJokeLayout);
m_vwJokeEditText=(EditText) this.findViewById(R.id.m_vwJokeEditText);
m_vwJokeButton=(Button) this.findViewById(R.id.m_vwJokeButton);
TextView tv=new TextView(this);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
What's the problem?
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
You can change lparams according to your needs
Here is a more general answer for future viewers of this question. The layout we will make is below:
Method 1: Add TextView to existing LinearLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);
// Add textview 1
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
// Add textview 2
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
}
Note that for LayoutParams you must specify the kind of layout for the import, as in
import android.widget.LinearLayout.LayoutParams;
Otherwise you need to use LinearLayout.LayoutParams in the code.
Here is the xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
</LinearLayout>
Method 2: Create both LinearLayout and TextView programmatically
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// NOTE: setContentView is below, not here
// Create new LinearLayout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundColor(0xff99ccff);
// Add textviews
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
// Set context view
setContentView(linearLayout);
}
Method 3: Programmatically add one xml layout to another xml layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
container.addView(view);
}
Here is dynamic_linearlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/flContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
And here is the dynamic_linearlayout_item.xml to add:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff66ff66"
android:padding="20px"
android:text="programmatically created TextView1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffdbdb"
android:layout_gravity="right"
android:layout_margin="10px"
android:textSize="18sp"
android:text="programmatically created TextView2" />
</LinearLayout>
I customized more #Suragch code. My output looks
I wrote a method to stop code redundancy.
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}
It can be called like
createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20);
Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.
RelativeLayout primary_layout = new RelativeLayout(this);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
primary_layout.setLayoutParams(layoutParam);
// FOR LINEAR LAYOUT SET ORIENTATION
// primary_layout.setOrientation(LinearLayout.HORIZONTAL);
// FOR BACKGROUND COLOR
primary_layout.setBackgroundColor(0xff99ccff);
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
20, 10, 20));
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20));
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="#string/font_light"
android:background="#drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with 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" >
<LinearLayout
android:id="#+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.
It Should be like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>