I have a simple demo with two buttons. They are laid out with a RelativeLayout at the top and bottom of the screen.
When I click one of them, I want them to switch places.
What is the best way to do that?
This is my res/layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageButton
android:id="#+id/android_button_1"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:src="#drawable/icon"
android:layout_alignParentTop="true" />
<ImageButton
android:id="#+id/android_button_2"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:src="#drawable/icon2"
android:layout_alignParentBottom="true" />
</RelativeLayout>
And this is my Activity:
public class HelloButtons extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton button1 = (ImageButton) findViewById(R.id.android_button_1);
final ImageButton button2 = (ImageButton) findViewById(R.id.android_button_2);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(HelloButtons.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(HelloButtons.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
}
}
Use something along these lines
RelativeLayout.LayoutParams lp1 = (LayoutParams) b1.getLayoutParams();
RelativeLayout.LayoutParams lp2 = (LayoutParams) b2.getLayoutParams();
lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
b1.setLayoutParams(lp1);
b2.setLayoutParams(lp2);
(and the opposite to revert them again) in you OnClickListeners
I would say the best way to do that is not to switch the actual ImageButton locations, but to instead switch the ImageButton images and keep track of the state inside your application so it can react to onClicks correctly.
Related
I have this problem: I want to put some Buttons at a certain locations, for example at the four squares of the screen (resolved) and I also want them to become red when clicking on each one, at exactly those locations (not resolved yet).
This is the main xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_weight="15"
android:orientation="vertical">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:components="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/layout1">
<Button
android:id="#+id/one"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#color/colorPrimary"/>
<Button
android:id="#+id/two"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:background="#color/colorPrimary" />
<Button
android:id="#+id/three"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary" />
<Button
android:id="#+id/four"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:background="#color/colorPrimary"/>
</RelativeLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
And this is the main java:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout1);
RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button btnTag = new Button(this);
btnTag.setLayoutParams(rel_btn);
btnTag.setBackgroundColor(Color.BLUE);
btnTag.setOnClickListener(listen);
layout.addView(btnTag);
}
private View.OnClickListener listen = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (pressed != null) {
Button button1 = (Button) pressed;
button1.setBackgroundColor(Color.BLUE);
}
Button button2 = (Button) view;
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(8, Color.RED);
button2.setBackgroundDrawable(drawable);
pressed = view;
}
in onCreate set up your buttons:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout1);
RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button one = (Button) findViewById(R.id.one);
one.setOnClickListener(listen);
Button two = (Button) findViewById(R.id.two);
two.setOnClickListener(listen);
Button three = (Button) findViewById(R.id.three);
three.setOnClickListener(listen);
Button four = (Button) findViewById(R.id.four);
four.setOnClickListener(listen);
and finally create your listener for all 4 of the buttons:
private View.OnClickListener listen = new View.OnClickListener() {
#Override
public void onClick(View view) {
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(8, Color.RED);
Button button = (Button) view;
button.setBackground(drawable);
}
};
If you were created Buttons in the layout then why are you adding it dynamically.
If you are using layout then inflate these buttons using "findViewById()". And when user will click perform the action to that or all buttons.
one.setBackgroundColor(Color.RED);
But if you are using dynamic button creation then store all 4 button id's which you are creating. Then perform something like this.
buttonId[index].setBackgroundColor(Color.RED);
Make your main class implement to View.OnclickListener
public class MainFragment extends Fragment implements View.OnClickListener {
private void setUpViews() {
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}}
#Override
public void onClick(View view) {
if(view instance of Button){
button.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
}
}
}
Well, if you give those buttons IDs, then you can change the color of them when you click it.
So if you tap on buttonID, do your logic and then change the color to buttonID.
// If you're in an activity:
buttonID.setBackgroundColor(getResources().getColor(R.color.red));
Add the color red to your color xml.
this can go inside of your onCreate. the buttonOne and buttonTwo at the IDs to the buttons in your XML.
This is the most BASIC way to do it. There are more ways, you can see those answers here too.
buttonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//logic here
}
});
buttonTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//logic here
}
});
When you have a listener changing something is relatively easy. You do not need to implement different methods or check every button one by one. Since Button is a View as well, do the following pseudo-code.
// You need this if part, if you have other views that having the same listener.
// Otherwise, you do not need this if check.
if(is Clicked View is Button) {
// Now here, take the clicked view, which we know it is a button and change its colour.
}
By the way, the code above will be inside the overridden method onClick.
EDIT
To clarify, I am adding a small chunk of code.
#Override
public void onClick(View view) {
// Checking if the clicked View is a Button or not.
if(view instanceof Button) {
// view.getId() returns an integer.
Button clickedButton = (Button) findViewById(view.getId());
// Now, change the button's colour.
clickedButton.setBackground(........);
}
}
Hope it helps. Have a nice day!
This is my child xml file(repeat.xml) which i want to add in main xml file
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginTop="200dp"
android:id="#+id/divider_parent"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<EditText
android:layout_width="350dp"
android:layout_height="50dp"
android:text="enter name here"
android:id="#+id/tv2"
android:layout_marginTop="90dp"/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="edit"
android:id="#+id/b1"
android:layout_marginTop="160dp"/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="save"
android:id="#+id/b3"
android:layout_marginTop="160dp"
android:layout_marginLeft="110dp"/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="button2"
android:id="#+id/b2"
android:layout_marginTop="160dp"
android:layout_marginLeft="220dp"/>
</RelativeLayout>
</FrameLayout>
this is my main.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:id="#+id/main"
tools:context="com.example.pawan.recyclerview.Main2Activity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main1"
android:layout_marginTop="200dp">
</RelativeLayout>
this is my main.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
RelativeLayout rl=findViewById(R.id.main1);
// RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.BELOW,R.id.main1);
for (int i=0;i<4;i++) {
View child = getLayoutInflater().inflate(R.layout.repeat, null);
rl.addView(child);
}
final EditText textView2=findViewById(R.id.tv2);
textView2.setEnabled(false);
Button button1=findViewById(R.id.b1);
Button button2=findViewById(R.id.b2);
Button button3=findViewById(R.id.b3);
final TimePicker tp=findViewById(R.id.timePicker);
tp.setEnabled(false);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView2.setEnabled(false);
tp.setEnabled(false);
Toast.makeText(getApplicationContext(),textView2.getText().toString()+" time is:" +tp.getCurrentHour() + ":" + tp.getCurrentMinute(),Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Main2Activity.this, Main3Activity.class);
startActivity(intent);
finish();
}
});
}
}
when i do not use the for loop in main.java and direct add child view only once it's working fine. But since i want to add it multiple times and on adding it using for loop multiple times the repeat.xml buttons stops working, thwy does'nt give any feedback i.e they becomes fixed(not clickable) and textview are not editable. Please give a solution for this :)
Your main error is here:
for (int i=0;i<4;i++) {
// add several layouts
}
// findViewById is outside the loop. So, this code will be executed only once and only for one view.
findViewById does not automatically changes all view with that ID. It just seach and return the first view with that ID. If you have more than one view using the same ID only the first view with that ID will be returned (which is your case because you are inflating same layout several times).
Also, you must find for a View not in the whole screen (since you have several views with same ID). You can search "inside" a specific layout or inside a view...
Instead of:
// Search a view inside the whole screen (root layout).
findViewById(R.id.tv2);
You can use:
// Search a view only inside child
child.findViewById(R.id.b1);
You should do something like:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
RelativeLayout rl=findViewById(R.id.main1);
for (int i=0;i<4;i++) {
View child = getLayoutInflater().inflate(R.layout.repeat, null);
rl.addView(child);
// -----------------------------------------------------------------
// Not that I'm looking for a R.id.tv2 but inside child view... and not in root view
// Use child.findViewById(R.id.tv2) instead of findViewById(R.id.tv2)
final EditText textView2 = child.findViewById(R.id.tv2);
textView2.setEnabled(false);
// SAME HERE
Button button1 = child.findViewById(R.id.b1);
Button button2 = child.findViewById(R.id.b2);
Button button3 = child.findViewById(R.id.b3);
final TimePicker tp = child.findViewById(R.id.timePicker);
tp.setEnabled(false);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView2.setEnabled(false);
tp.setEnabled(false);
Toast.makeText(getApplicationContext(),textView2.getText().toString()+" time is:" +tp.getCurrentHour() + ":" + tp.getCurrentMinute(),Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Main2Activity.this, Main3Activity.class);
startActivity(intent);
finish();
}
});
}
Note that are better ways to what you want such as ListView, RecyclerView etc... but this is another history.
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
I have a simple button in my layout. Setting leftMargin to the view actually showing different results.
my_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="hello pandora"/>
</RelativeLayout>
In my activity, I'm setting the leftMargin property to the Button.
Button leftBtn = (Button) findViewById(R.id.left_btn);
LayoutParams params = (LayoutParams) leftBtn.getLayoutParams();
params.leftMargin = 550;
If I set leftMargin as negative value or 0, its working fine, but If I set the value greater than the width of screen, it just resizing/compressing the button. I am expecting the button to go out of bounds like negative value.
I am expecting the button in the 3rd image to go out of bounds like the button in 1st image.
Please don't say to set the button layout_alignParentRight="true" in layout and rightMargin = -50in activity(this works) because I want to move the button from left to right.
I assume assigning a specific width larger than the screen size (eg. 1000 dp) to the parent RelativeLayout should solve your problem.
Also why do you want to make out-of-screen UI elements? What is the desired behaviour? Perhaps a transition animation would be better?
EDIT
I've tried the animation + storing the measured width of the Button. It seems to work.
Can you try this on GB?
MainActivity.java
public class MainActivity extends Activity {
final Context context = this;
Button mButton;
int mButtonWidth; // Measured width of Button
int amountToMove; // Amount to move the button in the x direction
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amountToMove = 600;
mButton = (Button) findViewById(R.id.button);
// Measure Button's width
mButton.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
mButtonWidth = mButton.getMeasuredWidth();
// Simple onClick listener showing a Toast
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"Hello Pandora clicked!",Toast.LENGTH_SHORT).show();
}
});
// Onclick listener for the other button
Button toggle = (Button) findViewById(R.id.toggle);
toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Animate the other button
TranslateAnimation a = new TranslateAnimation(0, amountToMove, 0, 0);
a.setDuration(1000);
// Finalize movement when animation ends
a.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationEnd(Animation animation) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mButton.getLayoutParams();
// Restore measured width and change left margin
lp.width = mButtonWidth;
lp.leftMargin = lp.leftMargin + amountToMove;
mButton.setLayoutParams(lp);
amountToMove = -amountToMove;
}
#Override
public void onAnimationStart(Animation animation) { /* Do nothing */ }
#Override
public void onAnimationRepeat(Animation animation) { /* Do nothing */ }
});
mButton.startAnimation(a);
}
});
}
}
activity_main.xml
<LinearLayout 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"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Pandora"
android:id="#+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Move the other button"
android:id="#+id/toggle"/>
</LinearLayout>
EDIT 2
It works on a GB Emulator too (the Button gets clipped, is clickable).
u can use max line=1 to show complete text in one line on button when you use leftMargin = 550;
try this
<Button
android:id="#+id/left_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:maxLines="1"
android:text="hello pandora"/>
Hello Edit your button property like this,
android:layout_gravity="center_horizontal"
android:singleLine="true"
and change parent layout to frameLayout
I want to add views on click of button. My screen has a text view and an edit text and a "Add More" button. on the click of button another set of text view and edit text should get appended to the screen. I am also planning to add scroll view once the my screen grows longer.
My Code snippet is as follows
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
text.setText("hello how are you?"); //this is just an example, I may want to add lot more here.
linearLayout.addView(text);
setContentView(linearLayout);
}
I know I am missing something very basic but I do not know what is that. :(
Please help.
First of all, you need to initialize each TextView with a reference to the context. So, in your onClick, given that it is in MyActivity.java:
public void onClick(View v) {
TextView text = new TextView(this);
text.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); // Or what you decide
text.setText("Your text");
linearLayout.addView(text);
}
Second, given that you have a call to setContentView in onCreate which also adds your linearlayout to the view, you do not need to call setContentView(linearLayout) each time the button is clicked.
you should first create a new TextView and EditText add it to the linearLayout using linearLayout.addView(). No need to call setContentView() you probably already added it.
This One help you
In your XML file
<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 file Like
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();
}
}
}
This one just example you can add any view like this