Add many CardViews with onclick method programmatically - java

I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.
Here is the CardView XML file (Before it was inside a Relative Layout)
<androidx.cardview.widget.CardView
android:id="#+id/cardviewClassesBlock1"
android:layout_width="330dp"
android:layout_height="75dp"
android:layout_marginTop="90dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background">
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:textSize="22sp"
android:fontFamily="#font/amiko_semibold"
android:textColor="#color/white"
android:text="Block A"/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_marginStart="10dp"
android:layout_below="#+id/textviewClassesBlock1"
android:background="#drawable/rounded_corner_edittext" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="5dp"
android:textColor="#color/white"
android:text="P - 0 | T - 0 | A - 0"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>

I have created a sample project for You.
First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
app:cardCornerRadius="10dp"
android:layout_margin="10dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher_background"
>
<TextView
android:id="#+id/textviewClassesBlock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:text="Block A"
android:textSize="22sp"
/>
<ImageView
android:layout_width="60dp"
android:layout_height="6dp"
android:layout_below="#+id/textviewClassesBlock1"
android:layout_marginStart="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="5dp"
android:text="P - 0 | T - 0 | A - 0"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
This is basically Your CardView with small changes.
Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<Button
android:id="#+id/butAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New Card"
/>
<Button
android:id="#+id/butDoSth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Do something"
/>
<androidx.appcompat.widget.LinearLayoutCompat
android:id="#+id/cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
android:id="#+id/includedLayoutFirst"
layout="#layout/card_base"
/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.
Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;
public class MainActivity extends AppCompatActivity
{
private int starter = 66; //ASCII code for `B`
LinearLayoutCompat cards;
Button buttonAdd;
Button buttonDoSth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = findViewById(R.id.cards);
buttonAdd = findViewById(R.id.butAdd);
buttonDoSth = findViewById(R.id.butDoSth);
buttonAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CardView newCard = new CardView(MainActivity.this);
getLayoutInflater().inflate(R.layout.card_base, newCard);
TextView t = newCard.findViewById(R.id.textviewClassesBlock1);
String current = Character.toString((char) starter++);
t.setText("Block " + current);
newCard.setTag(current); //
cards.addView(newCard);
}
});
buttonDoSth.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
findBlockAndDoSomething("B");
}
});
}
private void findBlockAndDoSomething(String name)
{
Log.d("MyTAG", "CLICK");
for (int i = 0; i < cards.getChildCount(); i++)
{
CardView selected = (CardView) cards.getChildAt(i);
if (selected.getTag() != null && selected.getTag().toString().equals(name))
{
// do something. E.g change block name
TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
textViewClassesBlock1.setText("Block XXX");
return;
}
}
}
}
Result (starter code and with adding new CardView):

Related

how do I add a reset button for my two TextViews in Android Studio

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="#+id/away"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="#string/away"
android:gravity="center"
android:textSize="20sp"/>
<TextView
android:id="#+id/score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="50dp"
android:onClick="score1"
android:text="#string/score" />
<TextView
android:id="#+id/home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:text="#string/home"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:id="#+id/score2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginBottom="50dp"
android:text="#string/_0"
android:textSize="20sp" />
<Button
android:id="#+id/two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="score2"
android:text="#string/score" />
<Button
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/reset"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textColor="#ff1100"/>
</LinearLayout>
I searched it on multiple websites but I still can't the answer. I also tried using the__setText("")it
didn't work as well as the the if() method. I have also tried the intent method also doesn't seem to
work, and many other codes , please help me because I am stuck at this bit , I know that it is simple but
I just can't find it. Thank you
The following codes will set the TextView score to blank when Button one is clicked
First approach
To use the android:onClick="score1" in your XML
Add this to your activity
TextView mTvScore1 = (TextView) findViewById(R.id.score)
public void score1(View v) {
mTvScore1.setText("");
}
Second approach
Button mBtn = (Button) findViewById(R.id.one)
TextView mTvScore1 = (TextView) findViewById(R.id.score)
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTvScore1.setText("");
}
});
Activity code
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTvScore1 = (TextView) findViewById(R.id.score);
Button mBtn = (Button) findViewById(R.id.one);
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
score1(v);
}
});
}
public void score1(View v) {
mTvScore1.setText("");
}
}

Radio button as tabs highlight when selected (Android Studio)

I am trying to create radio buttons that allows the users to select one of the three options. Once selected, the option should have a border, while the others do not.
Here is an image of what I am trying to create:
I'm not sure how to go about this. Any suggestions are greatly appreciated.
You could create a group of objects (which are the options) and programmatically ensure that only one of them can be selected.
selection could be presented as you wish it would be, I'd give a code example that imitates approximately the image you've attached. here's the structure:
XML file: CardViews with base of invisible FrameLayout (will be functioning as stroke), above the base is the cards' content
Java Class: setChecked(MaterialCardView selected) method that selects the chosen card (making it's 'stroke' visible) and checkedCard() that returns the selected card
so here's the code:
activity_main.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:background="#color/parentBackground"
tools:context=".MainActivity">
<com.google.android.material.card.MaterialCardView
android:id="#+id/public_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/cardBackground"
app:cardCornerRadius="5dp">
<FrameLayout
android:id="#+id/public_stroke"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/selectedCardStroke"
android:visibility="visible" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/cardBackground">
<com.github.abdularis.civ.CircleImageView
android:id="#+id/card1Icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:src="#mipmap/ic_public" />
<TextView
android:id="#+id/card1Label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/card1Icon"
android:text="Public Profile"
android:textAllCaps="false"
android:textColor="#color/cardLabelColor"
android:textSize="35sp" />
<TextView
android:id="#+id/card1Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/card1Label"
android:layout_alignStart="#id/card1Label"
android:text="Everyone can see your account. \nIncluding non followers."
android:textAllCaps="false"
android:textColor="#color/cardTextColor"
android:textSize="15sp" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="#+id/friends_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/public_card"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/cardBackground"
app:cardCornerRadius="5dp">
<FrameLayout
android:id="#+id/friends_stroke"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/selectedCardStroke"
android:visibility="invisible" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/cardBackground">
<com.github.abdularis.civ.CircleImageView
android:id="#+id/card2Icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:src="#mipmap/ic_friends" />
<TextView
android:id="#+id/card2Label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/card2Icon"
android:text="Friends Only"
android:textAllCaps="false"
android:textColor="#color/cardLabelColor"
android:textSize="35sp" />
<TextView
android:id="#+id/card2Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/card2Label"
android:layout_alignStart="#id/card2Label"
android:text="Connections nly. Only your friends \nand friends of friends can see your account."
android:textAllCaps="false"
android:textColor="#color/cardTextColor"
android:textSize="15sp" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="#+id/private_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/friends_card"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/cardBackground"
app:cardCornerRadius="5dp">
<FrameLayout
android:id="#+id/private_stroke"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/selectedCardStroke"
android:visibility="invisible" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/cardBackground">
<com.github.abdularis.civ.CircleImageView
android:id="#+id/card3Icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:src="#mipmap/ic_private" />
<TextView
android:id="#+id/card3Label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/card3Icon"
android:text="Private"
android:textAllCaps="false"
android:textColor="#color/cardLabelColor"
android:textSize="35sp" />
<TextView
android:id="#+id/card3Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/card3Label"
android:layout_alignStart="#id/card3Label"
android:text="Only you can see your account."
android:textAllCaps="false"
android:textColor="#color/cardTextColor"
android:textSize="15sp" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
</RelativeLayout>
MainActivity.java:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.google.android.material.card.MaterialCardView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public MaterialCardView cPublic, cFriends, cPrivate;
public FrameLayout sPublic, sFriends, sPrivate;
public ArrayList<MaterialCardView> cards;
public ArrayList<FrameLayout> strokes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cards = new ArrayList<>();
strokes = new ArrayList<>();
cPublic = findViewById(R.id.public_card);
cFriends = findViewById(R.id.friends_card);
cPrivate = findViewById(R.id.private_card);
cards.add(cPublic);
cards.add(cFriends);
cards.add(cPrivate);
sPublic = findViewById(R.id.public_stroke);
sFriends = findViewById(R.id.friends_stroke);
sPrivate = findViewById(R.id.private_stroke);
strokes.add(sPublic);
strokes.add(sFriends);
strokes.add(sPrivate);
cPublic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setChecked(cPublic);
}
});
cFriends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setChecked(cFriends);
}
});
cPrivate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setChecked(cPrivate);
}
});
}
public void setChecked(MaterialCardView selected) {
int index = cards.indexOf(selected);
FrameLayout stroke = strokes.get(index);
stroke.setVisibility(View.VISIBLE);
for (FrameLayout s : strokes) {
if (!s.equals(stroke)) {
s.setVisibility(View.INVISIBLE);
}
}
}
public MaterialCardView checkedCard() {
int index = 0;
for (FrameLayout s : strokes) {
if (s.getVisibility() == View.VISIBLE) {
index = strokes.indexOf(s);
}
}
return cards.get(index);
}
}
Hope it could help you (:

Linear layout not getting visible OnClickListener

I have two layouts. I want to keep one layout gone when the activity is loaded and it should be visible onClick of another layout. so I have added this code OnClickListener of the layout.
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(linearLayoutFrom.getVisibility() == View.GONE){
linearLayoutFrom.setVisibility(View.VISIBLE);
}else{
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
And have set visibility of the layout gone in xml file..
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/LinearLayoutAdditionalContactFrom">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/imageView13"
android:layout_marginLeft="20dp"
android:background="#drawable/ic_person_black_48dp"
android:layout_marginTop="05dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_marginRight="10dp"
android:drawableRight="#drawable/ic_expand_more_black_24dp"
android:text="Additional contact (optional)"
android:cursorVisible="false"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:layout_gravity="center"
android:visibility="gone"
android:id="#+id/LinearLayoutFrom">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:layout_weight="1"
android:hint="Name"
android:layout_gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:layout_weight="1"
android:hint="Phone"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="OR"
android:id="#+id/textView19"
android:layout_gravity="center" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/textView13"
android:layout_marginLeft="48dp"
android:hint="Input if you're not receiver" />
</LinearLayout>
Unable to understand whats going wrong.. The listener is not getting called at all.. Please help..
Your problem is that your EditText is capturing the click event when you click on it. If you click somewhere else in the LinearLayout it should work.
You can replace the EditText with a TextView if you don't need the user to edit the content.
Change
linearLayoutFrom.setVisibility(View.VISIBLE);
To
findViewById(R.id.YOURLAYOUTID).setVisibility(View.VISIBLE);
I think you can't access to local vars in sub methods
It Seems That Layout Visibility is Already set to GONE, so Onlick listener is not working on hidden View and it should not work too.
INVISBLE means you are trying to add a listener to a view which is not there. You can add the listener to a visible view only.
WORKAROUND
1) Try to make a dummy view which is visible but having the same color as background.
2) Try to set the listener for parent and check the position (whether the position does
belongs to INVISIBLE view).
Please try to set the onClickListener to the EditText and to the ImageView and no to the LinearLayout
The problem is that the Handler of the EditText is most important that the LinearLayout handler.
Almost you can try to make a break point to the OnClick and see what is happend
This is an example to explain you how to do that:
in MainActivity Class:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout linearLayoutFrom;
private LinearLayout additionalContactFrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
additionalContactFrom = (LinearLayout) findViewById(R.id.LinearLayoutAdditionalContactFrom);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"linearLayoutFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (additionalContactFrom.getVisibility() == View.GONE) {
additionalContactFrom.setVisibility(View.VISIBLE);
} else {
additionalContactFrom.setVisibility(View.GONE);
}
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"additionalContactFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
}
}
in xml file:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayoutAdditionalContactFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_dark"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayoutFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:background="#android:color/holo_green_light"
android:orientation="vertical"
android:visibility="gone" >
</LinearLayout>
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="48dp"
android:hint="Input if you&apos;re not receiver"
android:textAppearance="?android:attr/textAppearanceSmall" />
</FrameLayout>
This is very important that when you want add some view (for example
add a linearlayout to another linerlayout). you should use framelayout or
relativelayout(do not use linearlayout) for do that.

XML / Java Button Click to change TextView

I am realitavely new to Java coding and am trying to use a button press (in an Android App) to update a text view. The code I am currently using is causing my app to crash whenever I try to press the button.
Here is my XML
<LinearLayout>
<TextView
android:id="#+id/myTextView_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="calculateNewNumber"
android:text="Calculate New Number" />
</LinearLayout>
And Here is my Java
package com.example.android.myapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int startNumber = 0;
public void calculateNewNumber(View view) {
startNumber = startNumber + 1;
display(startNumber);
}
private void display(int number) {
TextView myTextView = (TextView) findViewById(
R.id.myTextView_text_view);
myTextView.setText("" + number);
}
}
Thanks for any help you can give.
The code itself works fine so the problem must be with your XML, assuming you have provided it in full here.
Using this XML, your MainActivity code works fine for me.
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:id="#+id/myTextView_text_view"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="calculateNewNumber"
android:text="Calculate New Number" />
</LinearLayout>
</RelativeLayout>

Programatically set layout_width of EditText in Android

So I have an application that dynamically adds a table row every time the "Add Row" button is pressed. The code attached is the code that runs when "Add Row" is pressed. What I am trying to do is have 3 EditTexts next to each other on the same row. In order to do that, I need to change the Layout_Width of each EditText so the first EditText doesn't cut the other two off the screen. I can't seem to figure out a way to properly do this and was wondering if anyone would help me out. After I figure out how to do that, the next step is to adjust the layout_width according to the screen size but thats later down the road. It needs to be done programmatically because a user can theoretically have as many rows as they want to.
private OnClickListener btnListener = new OnClickListener()
{
public void onClick(View v)
{
tablerow = new TableRow(getActivity());
ed1 = new EditText(getActivity());
ed1.setInputType(InputType.TYPE_CLASS_TEXT);
ed2 = new EditText(getActivity());
ed2.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
ed3 = new EditText(getActivity());
ed3.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
tablerow.addView(ed1);
tablerow.addView(ed2);
tablerow.addView(ed3);
table1.addView(tablerow);
}
};
I believe what you are looking for is LayoutParams and its "weight" value.
Try:
TableRow.LayoutParams params = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,1.0f);
ed1 = new EditText(getActivity());
ed1.setInputType(InputType.TYPE_CLASS_TEXT);
ed1.setLayoutParams(params);
The third value (1.0f) in the LayoutParams constructor is a weight...all EditTexts in that TableRow should end up the same width.
You can try next approach, it is based on xml. You will be able to play around with layout at table_row.xml.
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.a_mn_button_add_row:
onClickButtonAddRow();
break;
}
}
private void onClickButtonAddRow() {
TableLayout tableLayout = (TableLayout) findViewById(R.id.a_mn_table);
tableLayout.addView(View.inflate(this, R.layout.table_row, null));
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/a_mn_button_add_row"
android:onClick="onClick"
android:text="Add row"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="#+id/a_mn_table"
android:stretchColumns="0,1,2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
table_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<EditText
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableRow>
table_row.xml for use case with 3-1-2 proportions.
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="text" />
<EditText
android:layout_weight="1"
android:inputType="text"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<EditText
android:layout_weight="2"
android:inputType="text"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</TableRow>

Categories