Add custom layout to ConstraintLayout programmatically - android

Good day everyone.
I'm trying to a layout to a ConstraintLayout in a for-loop.
The layout is decalred as follows:
public class SingleMeal extends ConstraintLayout {
private TextView food_id;
private ImageButton spacer_minus;
private ImageButton spacer_plus;
private TextView food_quantity;
public SingleMeal(Context context) {
super(context);
init();
}
private void init(){
inflate(getContext(), R.layout.activity_single_meal, this);
this.food_id = findViewById(R.id.food_id);
this.spacer_minus = findViewById(R.id.spacer_minus);
this.spacer_plus = findViewById(R.id.spacer_plus);
this.food_quantity = findViewById(R.id.food_quantity);
}
public void setFood_id(String food_id) {
this.food_id.setText(food_id);
}
public TextView getFood_quantity() {
return food_quantity;
}
public ImageButton getSpacer_minus() {
return spacer_minus;
}
public ImageButton getSpacer_plus() {
return spacer_plus;
}
}
The xml of the layout is as follows:
<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=".selectMeals.SingleMeal">
<TextView
android:id="#+id/food_id"
android:layout_width="wrap_content"
android:layout_height="#dimen/edit_text_height"
android:layout_marginStart="#dimen/medium_space"
android:gravity="center"
android:textSize="#dimen/text_size"
android:layout_alignParentStart="true"/>
<LinearLayout
android:id="#+id/layout_food_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/medium_space"
android:orientation="horizontal"
android:layout_alignParentEnd="true">
<ImageButton
android:id="#+id/spacer_minus"
android:layout_width="#dimen/plus_minus"
android:layout_height="#dimen/plus_minus"
android:background="#drawable/minus"
android:contentDescription="#string/spacer"/>
<TextView
android:id="#+id/food_quantity"
android:layout_width="#dimen/info_quantity"
android:layout_height="#dimen/edit_text_height"
android:gravity="center"
android:text="0"
android:singleLine="true"
android:textSize="#dimen/text_size" />
<ImageButton
android:id="#+id/spacer_plus"
android:layout_width="#dimen/plus_minus"
android:layout_height="#dimen/plus_minus"
android:background="#drawable/plus"
android:contentDescription="#string/spacer"/>
</LinearLayout>
</RelativeLayout>
On the main activity I'm creating a new SingleMeal object, and populate it it's methods.
ConstraintLayout previousCourse = null;
for (Course course : meal.getCourses()) {
final SingleMeal food_container = new SingleMeal(this);
food_container.setId(View.generateViewId());
food_container.setFood_id(course.getName());
final TextView food_quantity = food_container.getFood_quantity();
ImageButton minus = food_container.getSpacer_minus();
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String foodQuantity = food_quantity.getText().toString();
int foodQuantityInt = Integer.parseInt(foodQuantity) > 0 ? Integer.parseInt(foodQuantity) - 1 : Integer.parseInt(foodQuantity);
food_quantity.setText(String.valueOf(foodQuantityInt));
}
});
ImageButton plus = food_container.getSpacer_plus();
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String foodQuantity = food_quantity.getText().toString();
int foodQuantityInt = Integer.parseInt(foodQuantity) + 1;
food_quantity.setText(String.valueOf(foodQuantityInt));
}
});
lunchCountainer.addView(food_container);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(lunchCountainer);
if (previousCourse == null)
constraintSet.connect(food_container.getId(), ConstraintSet.TOP , findViewById(R.id.txt_menu_date).getId(), ConstraintSet.BOTTOM,0);
else
constraintSet.connect(food_container.getId(), ConstraintSet.TOP , previousCourse.getId(), ConstraintSet.BOTTOM,0);
constraintSet.applyTo(lunchCountainer);
previousCourse = food_container;
}
I'm probably doing something very wrong as it goes trough the loop without any error, but it is not showing anything in the end.
The lunchContainer as previously said is a ConstraintLayout (inside a ScrollView):
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/lunch_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal|center_vertical"
android:isScrollContainer="true"
android:orientation="vertical"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical" />
Any idea?

It seems like you don't want a ConstraintLayout here, if you are stacking the items vertically I would suggest a LinearLayout set to Vertical.
Set the width of each item to MATCH_PARENT, then set the layout weight to be the same on each item, but make sure the height is set to WRAP_CONTENT so the sizes are the same for each item.
Not 100% sure this will work but this is the way to do it.
Or you could use a ListView, with your items within that, this will also handle scrolling etc for you.
Either option will work for you.

Related

Change background color of child views

I have a parent view and a child view. The child views are inflated programmatically. The child view has a TextView with some background. The TextView has a onclick event on it. What I want is when the user clicks the first TextView its background color should change and when the user selects the second one the background of the first textview should come back to its default background and the second one should change.
I have changed the background color but I am having difficulty in restoring the backgrounds. Here's my code:
My Parent View:
<com.google.android.flexbox.FlexboxLayout
android:id="#+id/viewCategoriesLinearlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap"
app:alignItems="stretch"
app:alignContent="stretch"
android:layout_marginTop="#dimen/_10sdp"
android:layout_marginLeft="#dimen/_5sdp"
android:layout_marginStart="#dimen/_5sdp" />
My Child View:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:id="#+id/categoryChip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#drawable/category_tag_background"
android:text="TAG"
android:layout_marginTop="#dimen/_25sdp"
android:paddingLeft="#dimen/_5sdp"
android:paddingTop="#dimen/_5sdp"
android:paddingBottom="#dimen/_5sdp"
android:paddingRight="#dimen/_5sdp"
android:layout_marginLeft="#dimen/_5sdp"
android:layout_marginRight="#dimen/_5sdp"
android:textColor="#color/textcolorLogin"
android:textSize="#dimen/_11ssp" />
<TextView
android:id="#+id/categorychipid"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="gone"/>
</LinearLayout>
This is how I'm inflating and changing background color:
FlexboxLayout categoryInformationHeader = view.findViewById(R.id.viewCategoriesLinearlayout);
final View editChildView = getActivity().getLayoutInflater().inflate(R.layout.tag_layout, null);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10,2,10,2);
editChildView.setLayoutParams(layoutParams);
editParentLL.addView(editChildView);
final TextView editTvChip = editChildView.findViewById(R.id.chip12345);
final String shelfShareCategoryTitle = crsEditShelfShare.getString(crsEditShelfShare.getColumnIndex("title"));
editTvChip.setText(shelfShareCategoryTitle);
editTvChip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTvChip.setBackgroundResource(R.color.colorPrimary);
}
});
When you you add a childview one at a time, save it on an array variable:
private ArrayList<TextView> childViews = new ArrayList<>(); //add this
#Override
public void onCreate(Bundle saveInstanceState) {
....
}
And upon clicking button, add it also on your arraylist:
childViews.add(editTvChip); //add it to your arraylist, so we can reset it
editTvChip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clearBackgrounds(); //call reset background first
editTvChip.setBackgroundResource(R.color.colorPrimary);
}
});
add this method to clear the textView background:
/**
* Reset all the background of each textViews
*
*/
private void clearBackgrounds() {
for (TextView textView : childViews) {
textView.setBackgroundResource(R.color.yourDefaultBackground);
}
}

Flip button positions in linear layout vertical

well i'm looking for a way to flip the button on a linear layout vertical here is a screen shot of the buttons
the xml code is
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:id="#+id/buttons_layout">
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iv_green"
android:layout_weight="1.0"
android:src="#drawable/leaf_green"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iv_other"
android:layout_weight="1.0"
android:src="#drawable/leaf_other"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iv_red"
android:layout_weight="1.0"
android:src="#drawable/leaf_red"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iv_yellow"
android:layout_weight="1.0"
android:src="#drawable/leaf_yellow"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
</LinearLayout>
what i want to do is that when i push flip button on (which is another button) i want to change the position of the current button i will explain in pics:
okay guys i used the idea that Arnab Told me about in the post below, well i want to randomly flip the image buttons so i did the following script:
public void onClick(View v) {
btnsLayout.removeAllViews();
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i = 0; i < 4; i++)
{
a.add(i);
}
Collections.shuffle(a);
btnsLayout.addView(Other, a.get(0).intValue());
btnsLayout.addView(Green, a.get(1).intValue());
btnsLayout.addView(Red,a.get(2).intValue());
btnsLayout.addView(Yellow,a.get(3).intValue());
}
the application is crashing the crash reason is:
java.lang.IndexOutOfBoundsException: index=2 count=1
what does it means ?
Thank you !
You can do this inside onCLick(View view) of Flip Button:
// Get all the views
LinearLayout btnsLayout = (LinearLayout) findViewById(R.id.buttons_layout);
ImageButton ivGreen = (ImageButton) findViewById(R.id.iv_green);
ImageButton ivOther = (ImageButton) findViewById(R.id.iv_other);
ImageButton ivRed = (ImageButton) findViewById(R.id.iv_red);
ImageButton ivYellow = (ImageButton) findViewById(R.id.iv_yellow);
// Remove views
btnLayout.removeView(ivGreen);
btnLayout.removeView(ivRed);
// ReAdd views in new index[Index 0 = position 1, Index 2 = position 3]
btnLayout.addView(ivRed, 0);
btnLayout.addView(ivGreen, 2);
Similarly :
// Remove views
btnLayout.removeView(ivOther);
btnLayout.removeView(ivYellow);
// ReAdd views in new index[Index 1 = position 2, Index 3 = position 4]
btnLayout.addView(ivYellow, 1);
btnLayout.addView(ivOther, 3);
First, you should rename the ids of the ImageButtons like :
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/first_leaf"
android:layout_weight="1.0"
android:src="#drawable/leaf_green"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/second_leaf"
android:layout_weight="1.0"
android:src="#drawable/leaf_other"
android:layout_gravity="fill_vertical"
android:scaleType="fitXY"
android:onClick="HandleClick" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/third_leaf"
android:layout_weight="1.0"
.../>
Then find your flip button in your java class and set an OnClickListener
like this:
myFlipButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
}):
Then, in the onClick function, perform the changes:
myFlipButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myFirstLeaf.setImageDrawable(getResources().getDrawable(R.drawable.leaf_red));
mySecondLeaf.setImageDrawable(getResources().getDrawable(R.drawable.leaf_yellow));
...
}
});
Hope it helps.
You can use the imgButton.setBackgroundResource(); method.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
imgButton1.setBackgroundResource(R.drawable.image3);
imgButton3.setBackgroundResource(R.drawable.image1);
}
});
If you want to swap the views you need to use a ViewGroup and you can set the index accordingly.
How do I change the position of a view in a Linear Layout.?
Hello Using Arnab Suggestion and some tuning i found a solution: the problem was that you need to insert the index 1 2 3 4 you can't randomly add the views to the linear layout.
public void addListenerOnButton() {
Button flip = (Button) findViewById(R.id.btn_flip);
final LinearLayout btnsLayout = (LinearLayout) findViewById(R.id.buttons_layout);
final ImageView Other = (ImageView) findViewById(R.id.iv_other);
final ImageView Green = (ImageView) findViewById(R.id.iv_green);
final ImageView Red = (ImageView) findViewById(R.id.iv_red);
final ImageView Yellow = (ImageView) findViewById(R.id.iv_yellow);
flip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnsLayout.removeAllViews();
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
a.add(i);
}
Collections.shuffle(a);
for (int k = 0; k<=3 ; k++){
if (a.get(0).intValue() == k) {
btnsLayout.addView(Other, a.get(0).intValue());
}
if (a.get(1).intValue() == k) {
btnsLayout.addView(Green, a.get(1).intValue());
}
if (a.get(2).intValue() == k) {
btnsLayout.addView(Red, a.get(2).intValue());
}
if (a.get(3).intValue() == k) {
btnsLayout.addView(Yellow, a.get(3).intValue());
}
}
}

Issue resizing ImageView programmatically

I am stuck trying to resize ImageView objects.
The issue is that when I set the width/height programmatically, I see the width/height change with the debugger tool in eclipse.
However, the image will not scale to the new size, and maintains its current ratios. In some cases it even puts the original image at its current size, and moving to a different activity will resize it (somewhat) correctly.
Screenshots:
After opening the app
http://imgur.com/ha9s9rL
After opening and closing a different activity
http://imgur.com/DrBIJaI
I would like for the images to sit next to each other, with the same width/height for each image.
onCreate() Method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_behavior);
listView = (ListView) findViewById(R.id.display_behavior_listview);
List<Behavior> behaviorList = parseCatagories();
List<View> views = getCatagoryViewsFromBehaviorList(behaviorList);
// Setup array adapter
BehaviorRow behaviorRows[] = getBehaviorRows(views);
int viewCount = 0;
View view;
for (BehaviorRow row : behaviorRows) {
if (viewCount < views.size()) {
view = views.get(viewCount);
row.setBehaviorOne(view);
viewCount++;
view = views.get(viewCount);
row.setBehaviorTwo(view);
viewCount++;
}
Log.i("BehaviorRowDat", row.toString());
}
BehaviorRowAdapter adapter = new BehaviorRowAdapter(getApplicationContext(), R.layout.catagory_row,
behaviorRows);
listView.setAdapter(adapter);
}
onWindowFocusChanged() Method:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ImageView catagoryOne;
ImageView catagoryTwo;
for (int i = 0; i < listView.getChildCount(); i++) {
catagoryOne = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_one);
catagoryTwo = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_two);
resizeImageView(catagoryOne);
resizeImageView(catagoryTwo);
}
}
Resize Image Code:
private ImageView resizeImageView(ImageView image) {
// Set length/width
int length = calculateLengthOfImages();
image.getLayoutParams().height = length;
image.getLayoutParams().width = length;
// Set Padding
int padding = calculatePaddingOfImages();
image.setPadding(padding, padding, padding, padding);
return image;
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
</LinearLayout>
Try changing the scaleType attribute in your ImageViews to:
android:scaleType="fitXY"
Alternatively, you can add this line in your resizeImageView() method:
image.setScaleType(ScaleType.FIT_XY);
Hope that helps!
Replace your xml with this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:scaleType="centerCrop" />
</LinearLayout>
In onCreate() of your activity, add this:
final ImageView imageView1 = (ImageView) findViewById(R.id.catagory_space_one);
final ImageView imageView2 = (ImageView) findViewById(R.id.catagory_space_two);
imageView1.post(new Runnable() {
#Override
public void run() {
imageView1.getLayoutParams().height = imageView1.getWidth();
imageView1.requestLayout();
}
});
imageView2.post(new Runnable() {
#Override
public void run() {
imageView2.getLayoutParams().height = imageView2.getWidth();
imageView2.requestLayout();
}
});
So what basically I did is I have stretched the two images' width equally to take the whole space in xml using layout_weight, then I have set the images' height to be like their respective widths in code. So now they are square-shaped.
Hope that helps.

Cardslib - How to set action for button events of custom cards on CardRecyclerView

I am trying to use Cardslib to create a RecyclerView with custom layout rows that would expand when I click a button on them. I followed customization guide and create both custom layout and custom card class, the cards do appear correctly like this
but I cant figure out how to set clicking event for view elements on this card.
In activity_main.xml, I have a CardRecyclerView:
<it.gmariotti.cardslib.library.recyclerview.view.CardRecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
card:list_card_layout_resourceID="#layout/my_cardview_layout"
android:id="#+id/my_recyclerview"/>
my_cardview_layout.xml:
<it.gmariotti.cardslib.library.view.CardViewNative xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:id="#+id/list_cardId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
card:card_layout_resourceID="#layout/my_material_card_layout"
style="#style/card_external"
android:layout_marginTop="12dp" />
my_material_card_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<it.gmariotti.cardslib.library.view.ForegroundLinearLayout
android:id="#+id/card_main_layout"
style="#style/card.native.main_layout_foreground"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="match_parent"
android:layout_height="210dp"
android:id="#+id/mycard_image"
android:src="#drawable/sea"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
android:id="#+id/mycard_title"
android:paddingTop="24dp"
android:paddingLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Subtitle"
android:id="#+id/mycard_subtitle"
android:paddingLeft="20dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/actions_padding"
android:paddingLeft="#dimen/actions_padding_left"
android:paddingRight="#dimen/actions_padding_left">
<TextView
android:id="#+id/mycard_suppaction1"
android:text="SHARE"
android:background="?android:selectableItemBackground"
android:layout_width="wrap_content"
style="#style/card.native.actions"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/mycard_suppaction2"
android:text="LEARN MORE"
android:background="?android:selectableItemBackground"
android:layout_width="wrap_content"
style="#style/card.native.actions"
android:layout_height="wrap_content"/>
</LinearLayout>
</it.gmariotti.cardslib.library.view.ForegroundLinearLayout>
<FrameLayout
android:id="#+id/card_content_expand_layout"
style="#style/card.native.main_contentExpand"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</FrameLayout>
My main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Card> cards = new ArrayList<Card>();
//CardViewNative cardView = (CardViewNative) findViewById(R.id.myMaterialCardView);
for(int i = 0; i<3; i++) {
MyMaterialCard card = new MyMaterialCard(this);
CardExpand expand = new CardExpand(getApplicationContext());
//Set inner title in Expand Area
expand.setTitle(" Hidden content");
card.addCardExpand(expand);
card.setId("" + i);
cards.add(card);
}
CardArrayRecyclerViewAdapter mCardArrayAdapter = new CardArrayRecyclerViewAdapter(this, cards);
//Staggered grid view
CardRecyclerView mRecyclerView = (CardRecyclerView) this.findViewById(R.id.my_recyclerview);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Set the empty view
if (mRecyclerView != null) {
mRecyclerView.setAdapter(mCardArrayAdapter);
}
}
my custom card class:
public class MyMaterialCard extends Card {
ImageView mImage;
TextView mTitle;
TextView mSubtitle;
TextView mActionButton1;
TextView mActionButton2;
public MyMaterialCard(Context context) {
super(context, R.layout.my_cardview_layout);
}
public MyMaterialCard(Context context, int innerLayout) {
super(context, innerLayout);
}
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
mImage = (ImageView) view.findViewById(R.id.mycard_image);
mTitle = (TextView) view.findViewById(R.id.mycard_title);
mSubtitle = (TextView) view.findViewById(R.id.mycard_subtitle);
mActionButton1 = (TextView) view.findViewById(R.id.mycard_suppaction1);
mActionButton2 = (TextView) view.findViewById(R.id.mycard_suppaction2);
mActionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "action 1", Toast.LENGTH_SHORT).show();
}
});
ViewToClickToExpand viewToClickToExpand =
ViewToClickToExpand.builder()
.setupView(mActionButton2);
setViewToClickToExpand(viewToClickToExpand);
}}
I think the problem maybe the my_cardview_layout.xml, however, if i set card:list_card_layout_resourceID="#layout/my_material_card_layout"
in recyclerview and
public MyMaterialCard(Context context) {
super(context, R.layout.my_material_card_layout);}
they will not appear as cards:
have been working on this for 2 days and still can not get those buttons to work ( tried using Cardslib material card but when add expand, nothing happened). Really appreciate any help, thank you!
On main activity, add function setOnClickListener:
for(int i = 0; i<3; i++) {
MyMaterialCard card4 = new MyMaterialCard(this);
card.setOnClickListener(new Card.OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Toast.makeText(view.getContext()," Click on ActionArea ",Toast.LENGTH_SHORT).show();
}
});
CardExpand expand = new CardExpand(getApplicationContext());
//Set inner title in Expand Area
expand.setTitle(" Hidden content");
card.addCardExpand(expand);
card.setId("" + i);
cards.add(card4);
}
I think this could help some people, I hope not you xD (1 year, 10 months ago)

Android: many equal Buttons, onclick doesn't work for certain

I have seven equal Buttons in LinearLayout
<?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:layout_gravity="center"
android:weightSum="7" >
<Button
android:id="#+id/btn_mon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#color/white"
android:text="0" />
<Button
android:id="#+id/btn_tus"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_wen"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_thu"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_fri"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_sat"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
<Button
android:id="#+id/btn_sun"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="0"
android:background="#color/white"
android:layout_weight="1"/>
</LinearLayout>
Their OnClickListener is also equal (and initializing too):
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.calendar_row, null);
}
final Button btn_mon = (Button)convertView.findViewById(R.id.btn_mon);
final Button btn_tus = (Button)convertView.findViewById(R.id.btn_tus);
final Button btn_wen = (Button)convertView.findViewById(R.id.btn_wen);
final Button btn_thu = (Button)convertView.findViewById(R.id.btn_thu);
final Button btn_fri = (Button)convertView.findViewById(R.id.btn_fri);
final Button btn_sat = (Button)convertView.findViewById(R.id.btn_sat);
final Button btn_sun = (Button)convertView.findViewById(R.id.btn_sun);
btn_mon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_mon, weekdays.get(0).data); }});
btn_tus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_tus, weekdays.get(1).data); }});
btn_wen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_wen, weekdays.get(2).data); }});
btn_thu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_thu, weekdays.get(3).data); }});
btn_fri.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_fri, weekdays.get(4).data); }});
btn_sat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_sat, weekdays.get(5).data); }});
btn_sun.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_sun, weekdays.get(6).data); }});
onCalBtnClick method:
private void onCalBtnClick(Button btn, int day){
Log.d("debug", String.valueOf(day));
btn.setTextColor(mContext.getResources().getColor(R.color.orange));
//selectedYear, month are global
Intent intent = new Intent();
intent.putExtra("year", selectedYear);
intent.putExtra("month", month);
intent.putExtra("day", day);
setResult(RESULT_OK, intent);
finish();
}
However, if I put Log.d into onCalBtnClick method (it is called from each clicklistener), only middle three buttons work. Two buttons from left side (btn_mon, btn_tus) and two buttons from right side (btn_sat, btn_sun) don't react on user click. Middle buttons work fine.
This is similar question Android LinearLayout make button doesn't work but my layout file corresponds to pattern in the answer there and buttons don't work nevertheless
UPDATE
When I removed fixed button height and width in layout file (from 50dp to wrap_content), all buttons started to work!
However, now it doesn't look as needed. There's space needed between text's on buttons.
And main question: WHY?
If you using weights in your layout, you are telling that it should be filled with some objects with some proportions. It just opposite to "wrap_content". With weights outer layout defines size of inner views, while "wrap_content" means that outer layout size is defined by inner views.
Please decide what approach is better in that case - removing weights or fixed inner views sizes.
set your Linear Layout's Width and Height to FILL_PARENT .it will work for sure.
Try to declare all your setOnClickListener for buttons outside of your adapter class and after initialization of weekdays array.
That will solve your problem.
Or try to set condition like this for all buttons :
if (btn_mon != null && position < weekdays.size()) {
btn_mon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { onCalBtnClick(btn_mon, weekdays.get(0).data); }});
}

Categories

Resources