android How to add button over other button? - android

I'm trying to add button on other button exactly on same position with same width,and height.
I thought i can do that like these codes,
public class MainActivity extends AppCompatActivity {
Button b1;
LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (LinearLayout)findViewById(R.id.activity_main);
b1 = (Button)findViewById(R.id.b1);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ViewGroup.LayoutParams size = new ViewGroup.LayoutParams(b1.getWidth(),b1.getHeight());
int[] locations = new int[2];
b1.getLocationInWindow(locations);
Button a = new Button(this);
a.setLayoutParams(size);
a.setText("new Button");
a.setX(locations[0]);
a.setY(locations[1]);
root.addView(a);
}
}
and XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="semo.msoft.myapplication.MainActivity">
<Button
android:id="#+id/b1"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"/>
</LinearLayout>
but, result was like this,
resultImage
I thought it should be correct but it seems be wrong, new button had little bit smaller width and height. Additionally , the position of new button was totally wrong.. I don't know why,, someone who know about this, please help

The following code is working perfectly fine on my machine. I basically just changed the way you are setting LayoutParams:
int[] locations = new int[2];
b1.getLocationInWindow(locations);
Button a = new Button(this);
a.setLayoutParams(b1.getLayoutParams());
a.setX(locations[0]);
a.setY(locations[1]);
a.setText("new Button");
frameLayout.addView(a);
PS: You need to change the root to <FrameLayout>. LinearLayout just isn't made to handle overlapping views.

Related

setLayoutParams called from button OnClickListener

I'm trying to resize ImageView on button click. I don't know why but setLayoutParams works when I call it in onCreate method, but not working when use it inside button's OnClickListener. Did I miss something?
ImageView myImageView;
Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
myImageView = findViewById(R.id.viewtest);
myButton = (Button)findViewById(R.id.buttontest);
resizeImageView(); // resize when called here
myButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
resizeImageView(); // NOT resize when called here
}
});
}
private void resizeImageView() {
Toast.makeText(getApplicationContext(), "Resize", Toast.LENGTH_LONG).show();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)myImageView.getLayoutParams();
params.height = 300;
params.width = 300;
myImageView.setLayoutParams(params);
}
XML layout. I'm using LinearLayout inside of RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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"
tools:context=".ResultActivity">
<android.widget.LinearLayout
android:id="#+id/lineartest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:id="#+id/viewtest"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="centerCrop"
android:layout_centerVertical="true"
app:srcCompat="#mipmap/ic_launcher_round"
android:background="#444"
/>
</android.widget.LinearLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttontest"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="test"/>
</android.widget.RelativeLayout>
I just checked. This works fine in case of ImageView.
Maybe you are resizing it multiple times. Means If you have already called resresizeImageView() in onCreate method and you call it again in OnClick method , the resizing won't be visible because it already has the size you are resizing to.
In xml, you have AppCompatButton but in java you have defined as Button. Change AppCompatButton to Button in xml Or in java, Button to AppCompatButton.
I used your code, to create a new project, and just commented out the first call to resizeImageView() and it works fine when resizeImageView() is called in onClick()
As Derek answered, maybe you're already setting the same bounds to the ImageView during onCreate() which you wish to update in button click.
Also, just a suggestion:
Try adding the property android:layout_below="#id/lineartest" to your AppCompatButton.
Change android:layout_height="wrap_content", so you can view the changes happening to the ImageView.
Try this one
public class SomeActivity extends Activity {
public static final float screenWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_company);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
}
}
And after declare this implementation:
Button mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float scale = SomeActivity.screenWidth / view.getWidth();
if(view.getScaleX() == 1) {
view.setScaleY(scale);
view.setScaleX(scale);
} else{
view.setScaleY(1);
view.setScaleX(1);
}
}
});
OK. I've found solution. I use some async task that affects ImageView (loading image). When I disabled it resize button started to work as excepted. Thanks for your help.

Adding views programatically to a relative layout within a scrollview

Please bear with me as I am new to the use of Views and Layouts.
I am trying to create an application in which the user can enter a text field, press a button and have a new text field appear and they can continue adding text fields in this way.
My solution was to have the top level be a scrollview and then have a relative view as a child within that(this way I can then programatically insert more editviews in my code with the OnClick() listener.
I have seen and read a couple of other posts pertaining to relative views but it seems there is still something that I am missing. I have tried
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create_accounts"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nic.mybudget.CreateAccountsActivity">
<RelativeLayout
android:id="#+id/activity_create_accounts_relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/activity_name"
android:inputType="textAutoComplete"
android:layout_alignParentTop="true"
android:id="#+id/activity_createAccounts_relativeLayout_activityName"/>
<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/activity_createAccounts_relativeLayout_activityName"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_addButton" />
<Button
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/activity_create_accounts_relativeLayout_activityName_addButton"
android:layout_centerHorizontal="true"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_saveButton" />
</RelativeLayout>
And here is the Code where I try to add new editviews.
public class CreateAccountsActivity extends Activity {
static private final String TAG = "MAIN-Activity";
int numAccounts = 0;
int lastAccountID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_accounts);
final RelativeLayout Relative = (RelativeLayout) findViewById(R.id.activity_create_accounts_relativeLayout);
final TextView oldAccount = (TextView) findViewById(R.id.activity_createAccounts_relativeLayout_activityName);
final TextView newAccount = new TextView(this);
final Button addNewAccountButton = (Button) findViewById(R.id.activity_create_accounts_relativeLayout_activityName_addButton);
addNewAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "addNewAccountOnClick");
numAccounts = numAccounts+1;
int newAccountID = oldAccount.getId() + numAccounts;
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
newAccount.setLayoutParams(rlp);
newAccount.setHint("Hint" );
newAccount.setId(newAccountID);
Relative.addView(newAccount);
RelativeLayout.LayoutParams blp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
blp.addRule(RelativeLayout.BELOW, newAccountID-1);
addNewAccountButton.setLayoutParams(blp);
}
});
}
}
As you can see what I am trying (and failing) to do is add the new edit view at the top of the page and simply push everything else down the page. What am I getting wrong here with the relative layout?
Any help is appreciated.
First thing View with id activity_createAccounts_relativeLayout_activityName is EditText and you are casting it with TextView so that is wrong cast it to EditText.
And to your actual problem:
You are using same EditText instance with variable newAccount and adding it again in relative layout if you want to add one more EditText in relative layout you have to initialise EditText inside onclicklistener.
Just add one line newAccount= new EditText(context)in your onclicklistener code before line numAccounts = numAccounts+1;
Happy Coding !

Set button centerHorizontal

I know there are some questions about this topic but neither did work for me. I have created a simple button in a RelativeLayout and when I click on it I'd like the button to jump in the middle of the screen. So I have to set the button to CenterHorizontal and CenterVertical programatically.
Here is my code to set the button centerHorizontal:
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
final RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)btn.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL,0);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.setLayoutParams(layoutParams);
}
});
}
And here is my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android: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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
When I press the button nothing happens. If anyone has an idea how to fix it please response.
So i found a few problems in your code:
1. You have to add the rule after a button click because you create a reference betwen the variable "layoutParams" and the object.
2.You need to get rid of the existing rules.
Sample code:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
btn.setLayoutParams(layoutParams);
}
});
You have to remove your align left rules which you have defined in the xml.
Button btn = (Button)findViewById(R.id.button);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) btn.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 1);
lp.removeRule(RelativeLayout.ALIGN_PARENT_START);
lp.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
btn.setLayoutParams(lp);
keep in mind that RelativeLayout.LayoutParams.removeRule is only supported for API >= 17

Create certain number of EditTexts based on User Input in Android

How would I display a certain number of EditTexts on an Android layout based on user input? For example, I am creating a simple GPA Calculator app, and I need the multiple EditTexts based on however many classes the user is taking. I want to make the range from 1 to 6 classes. Would the easiest way be to create 6 EditText fields and only display however many the user needs when he or she specifies, or is there a better way to do this?
Thank you!
You can create the EditText programatically.
btnClick.setOnClickListener(new OnClickListener(){
//loop based on classes needed
EditText myEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new LayoutParams(..., ...)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
myLayout.addView(myEditText);
});
Check this out.
// Try this way,hope this will help you...
**activity_main.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edtNoCreate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter no EditText wan create"
android:inputType="number"/>
<Button
android:id="#+id/btnCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="5dp">
<LinearLayout
android:id="#+id/lnrDynamicEditTextHolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
**MainActivity.java**
public class MainActivity extends Activity{
private LinearLayout lnrDynamicEditTextHolder;
private EditText edtNoCreate;
private Button btnCreate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrDynamicEditTextHolder = (LinearLayout) findViewById(R.id.lnrDynamicEditTextHolder);
edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);
btnCreate = (Button) findViewById(R.id.btnCreate);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edtNoCreate.getText().toString().length()>0) {
try {
lnrDynamicEditTextHolder.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
int length = Integer.parseInt(edtNoCreate.getText().toString());
for (int i=0;i<length;i++){
EditText editText = new EditText(MainActivity.this);
editText.setId(i+1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("EditText "+(i+1));
lnrDynamicEditTextHolder.addView(editText);
}
}
}
});
}
}
for(int i=0;i<3;++i)
{ LinearLayout layout=(LinearLayout)findViewById(R.id.linearLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
EditText edttext= new EditText(this);
edttext.setId(i);
edttext.setLayoutParams(params);
layout.addView(edttext);}
}

Android: Adding buttons at runtime

I'm trying to add some buttons in my TableRow, at runtime. My TableRow has this structure:
<TableRow
android:layout_marginTop="100px"
android:gravity="bottom"
android:paddingTop="50px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/riga1">
<Button
android:textSize="32px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonOK2"
android:text="YES"
android:onClick="setResult"/>
</TableRow>
And my java code is:
TableRow tr = (TableRow) findViewById(R.id.riga1);
Button b = new Button(this);
b.setText("button 1");
b.setId(1);
b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tr.addView(b);
Button b1 = new Button(this);
b1.setText("button 2");
b1.setId(2);
b1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tr.addView(b1);
But this seems not to work. In my activity I can see only the button defined in the xml file.
Another problem is that if I set in the related TableLayout the parameter:
android:stretchColumns="*"
I must insert (in xml file) at least one button in the TableRow of the aforementioned TableLayout, otherwise I obtain a "division by zero error" near streatchColumns What can I do, in order to let the tableRow empty?
I think that your problem is that you are using the wrong LayoutParams object for your TextViews try this:
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
and then set this layoutParams object:
b.setLayoutParams(layoutParams);
Instead of table layout you should use relative layout it's work for me try it
In Your XML File Like this
<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:id="#+id/myMainRelativeLayout"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="47dp"
android:text="Add Button" />
And your java code like bellow
public class MainActivity extends Activity implements
android.view.View.OnClickListener {
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnAdd) {
RelativeLayout rl = (RelativeLayout)findViewById(R.id.myMainRelativeLayout);
Button btn = new Button(this);
btn.setId(1234);
btn.setText("Add Button Runtime");
btn.setOnClickListener(this);
rl.addView(btn);
}
if(v.getId() == 1234)
{
Toast.makeText(getApplicationContext(), "This is Your New Button", Toast.LENGTH_LONG).show();
}
}
}
try this one it's really work
first you need to find the button using this statement
btn=(Button)findViewById(R.id.Button1);
than you can set the visibility using this:
btn.setVisibility(View.INVISIBLE);
Then you can set the Visibility using the statement:
btn.setVisibility(View.VISIBLE);

Categories

Resources