I just want to dynamicly add buttons to my Layout when i want to.
The buttons should be like this XML Button:
<Button android:text="Text"
android:gravity="bottom"
android:textSize="10dp"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:background="#drawable/attack1"
android:layout_height="wrap_content"
android:id="#+id/workingButton">
</Button>
.
public class GravityIssueActivity extends Activity
{
LinearLayout layout;
Button newButton;
Button buttonByXml;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//the button in the xml file
buttonByXml = (Button)findViewById(R.id.workingButton);
layout = (LinearLayout)findViewById(R.id.layoutToInsert);
//my new programatically "born" button
newButton = new Button(this);
//Setting the properties as i want
newButton.setText("Text");
newButton.setTextSize(10);
newButton.setTextColor(Color.WHITE);
newButton.setBackgroundResource(R.drawable.attack1);
// Gravity = Bottom !!!!!!!!!!
newButton.setGravity(Gravity.BOTTOM);
// getting the XML buttons params just for case...
newButton.setLayoutParams(new LayoutParams(buttonByXml.getLayoutParams()));
//Adding my new Button to the layout
layout.addView(newButton);
}
}
And here is an image of the results:
How is it possible to became different result when I copy all the attributes?
If you want to create dynamic view (like Button,textview etc) then just use this code and run it in your application.
MyActivity.java://your java file
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
Button btn = new Button(this)
btn.setText("My Dynamic Button);
btn.setMinLines(1);
btn.setMaxLines(3);
ll.addView(et);
In XML File:
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignBottom="#+id/TextView01"
android:layout_below="#+id/relativeLayout1"
android:orientation="vertical" >
You can absolutely create buttons in code but it's not considered a best-practice unless you have a good reason for dynamically creating the controls. Check out this post Add an array of buttons to a GridView in an Android application.
Try using
Button b = new Button();
This gives you a View instance that can be added to your current parent activity or fragmnet view. For a full reference of possible settings look at http://developer.android.com/reference/android/widget/Button.html
You can use all the set methods provided by parent views in the object hierarchy.
If you need to align text to the bottom of the button, all you need is:
Button button = ...
//apply required paramteres
button.setGravity(Gravity.BOTTOM);
use below code.you also add other parameters
Button submit=new Button(this);
LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(25, 0, 25, 0);
submit.setLayoutParams(params);
submit.setText("Attack");
submit.setTextSize(10);
submit.setTextColor(getResources().getColor(R.color.white));
submit.setBackgroundResource(R.drawable.attack);
Related
What is the difference between Button button= (Button) findViewbyID(R.id.button); and Button button = new Button(this);?
There are two approach to create and set button.
By using xml file:
In your activity.xml you will write code like this:
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Press" />
Then you have to set it's reference in activity class file like this:
Button button=(Button) findViewbyID(R.id.button);
Programatically inside Activity class like:
Button myButton = new Button(this);
myButton.setText("Press");
LinearLayout layout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout .addView(myButton, lp );
new Button you're just creating a button on your application memory (RAM memory). This button is not on the screen and it's not inside any layout until you call addView(buton) somewhere.
findViewById you're just FINDING and getting the reference of a view that have already been created and that is already in the layout and that will be drawn to the screen during drawn operation.
I have created an Activity that uses the ViewFlipper to Switch between Different elements. Each element represents an Item in a store. I would like to add a "Buy" Button to each View. I am however not sure how to do this, since all the views use the default layout i have created. I have added the information like the Price of the Item etc Programmatically. So i am uncertain how to add a listener to the button, since they will all refer to the same button in the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/credit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="220dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="104dp" />
<TextView
android:id="#+id/credit_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/credit_button"
android:layout_alignTop="#+id/credit_button"
android:layout_marginRight="22dp"
android:layout_marginTop="21dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="normal" />
<TextView
android:id="#+id/credit_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/credit_button"
android:layout_alignRight="#+id/credit_type"
android:layout_centerVertical="true"
android:layout_marginBottom="30dp"
android:layout_marginLeft="15dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
As you can see, the Button id is "Credit Button". So now to be able to differentiate between the different store items' buttons what would i have to do?
Note, i am adding store items dynamically as well, so i cant simply create all the views separately using xml.
OK HERE IS THE UPDATED ANSWER. I used everyones responses below to fix teh issue. So Thank you all :)
// PerkView
View PerkView = View.inflate(this, R.layout.store_category, null);
viewFlipper.addView(PerkView);
Button perkButton = (Button)
PerkView.findViewById(R.id.StoreCatItem);
// TitleView
View TitleView = View.inflate(this, R.layout.store_category, null);
viewFlipper.addView(TitleView);
Button titleButton = (Button)
TitleView.findViewById(R.id.StoreCatItem);
// ProfileView
View ProfileView = View.inflate(this, R.layout.store_category, null);
viewFlipper.addView(ProfileView);
Button profileButton = (Button)
ProfileView.findViewById(R.id.StoreCatItem);
I simply Created Multiple Views Programmatically, and then retrieved the buttons from those views afterwards. I then added the listeners to the buttons as follows:
perkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), Perks.class);
i.putExtra("player", player);
startActivity(i);
}
});
titleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), Titles.class);
i.putExtra("player", player);
startActivity(i);
}
});
Thanks A lot :)
There are two ways you can handle the button click distinctly,
At the time of inflating layout for each store, add the button listener with onClick() method there only.
Or you can assign some uniqueId or flag to each store and then handle button click of store by this uniqueID.
Usually you solve this by following stack:
fragment -has-> list -has-> adapter -has-> list of items
Normally if you present one item per screen and you want to swipe between you should use ViewPager with FragmentStatePagerAdapter (allows removing items from ViewPager if needed).
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
For more items in one screen use ListView with BaseAdapter as it allows better control over item view and ListView will recycle views as you scroll or fling.
http://developer.android.com/guide/topics/ui/layout/listview.html
Set unique tag for each store button, in code you can differentiate with respect to tags.Tag is just piece of information you want set for any view, u can use it.Implement on click listener in your activity and then set that to all buttons, so all buttons click run through same code where you can easily diffrentiate between ur store buttons with respect to tags.
like below how you can set and get tag
// for setting tag
Button button = (Button) findViewById(R.id.button1);
button.setTag("unique_tag");
// get tag and then differentiate with the unique_tg
button.getTag();
You can easily create your button programmatically like so :
Button b = new Button(this); // where this = your context
b.setText("Buy");
// b."other attribute" = "other value";
b.setTag("Awesome blue shirt");
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Button buy = (Button) v;
String article = b.getTag();
// do some stuff
}
});
container.addView(b);
You can identify the buy button using its tag, as seen here.
I am quite new to developing apps. Still I would have thought that this is a basic action, so if there is already a solved thread I would be OK with the link. But since I am searching for over 2 hours for this I am asking anyway:
I want to dynamically add an element to my layout every time the user clicks a button.
By now I have this:
XML (R.layout.game.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_choice"
android:onClick="submitChoice"/>
</LinearLayout>
Java
public void submitChoice(View view)
{
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText("text");
LinearLayout ll = new LinearLayout(this);
ll.addView(View.inflate(ll.getContext(), R.layout.game, null));
ll.addView(textView);
setContentView(ll);
}
Since the XML file does not change, it only works once.
So how can I add a second text when the user clicks the button a second time (without changing the XML file)? Examples are appreciated.
The problem comes from this line, that recreate the whole layout every time:
LinearLayout ll = new LinearLayout(this);
You should define it and setContentView(ll) outside the submitChoice function. Then on click only create and add the textView , then call ll.invalidate(); to see the changes.
Something like:
LinearLayout ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
ll = (LinearLayout) findViewById(R.id.ll_game);
}
// More code...
public void submitChoice(View view) {
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText("text");
ll.addView(textView);
ll.invalidate();
}
where ll_game is the id you have to set in xml for your LinearLayout.
I am trying to create a coach mark for Android.
I want it to be absolutely full screen, and my app has an ActionBar. So, the solution suggested by Commons, which is basically inflate a FrameLayout after setContentView(view); does not work, because the FrameLayout would be below the ActionBar. And I want it full screen.
So, I took a screenshot of my screen and drew some coach marks with photoshop and created a .png file of it. I then load this png file with the following code:
public void onCoachMark(){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.activity_main_coach_mark);
dialog.setCanceledOnTouchOutside(true);
//for dismissing anywhere you touch
View masterView = dialog.findViewById(R.id.parent);
masterView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
preferences.edit().putBoolean("COACH_MARK_MAIN_SHOWN", true).commit();
}
});
dialog.show();
}
This works perfectly on my phone, but as we all know, we have thousands of Android models. With another model, this is how it looks like:
I have tried using the ShowcaseView project but, apparently, it does not work with ActionBar buttons. And I need that.
Can anyone help me with this?
Simply add this to your onCoachMark method:
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
Just think simply
Step 1: Open your main_activity layout file
Step 2: In the main_activity layout check Root Layout, If the Root Layout not start with FrameLayout, change it to FrameLayout.
Step 3: Converting from other layout to FrameLayout it may cause layout problem, you have to fix it. Step 4: Create another FrameLayout that will overlay top of your existing view.
Example:
<FrameLayout ...>
.....
....
<FrameLayout
android:id="#+id/c_mark"
.../>
</FrameLayout>
Step 5: Position your new FrameLayout by layout gravity. Example: android:layout_gravity="top|right"
Step 6: Hide that view by default
Step 7: Now in your Main Activity use this Id and play with property. Just custom design your c_mark FrameLayout set id and use it. Let me Give you example.
Let me Give you example.
Example: MainActivity.class
FrameLayout coachMarkLayout = findViewById( R.id.c_mark);
coachMarkLayout.setVisibility( View.VISIBLE );
FrameLayout messageBoxLayout = (FrameLayout) rootFrameLayout.getChildAt( 0 );
LinearLayout linearLayout = (LinearLayout) messageBoxLayout.getChildAt( 1 );
Button skipButton = (Button) linearLayout.getChildAt( 0 );
skipButton.setOnClickListener( v -> {
rootFrameLayout.setVisibility( View.GONE );
} );
Button nextButton = (Button) linearLayout.getChildAt( 1 );
nextButton.setOnClickListener( v -> {
rootFrameLayout.setVisibility( View.GONE );
// you can add second coarch mark here
} );
main_activity.xml
<FrameLayout
android:id="#+id/c_mark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:visibility="gone">
<FrameLayout
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp">
<include layout="#layout/layout_message_box"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal">
<include layout="#layout/layout_arrow"/>
</FrameLayout>
</FrameLayout>
If I have a page whose layout is designated by XML code, but I want to possibly create a few radio buttons, say, in the middle, but decide that at runtime, how would I do it? I'm new to Android so I'm taking a stab in the dark. Would something like this work?
In the XML, add a LinearLayout to the middle of the page's XML like this:
<LinearLayout android:id="#+id/LinLayBut"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
And then in the java something like this:
public void setupRadioButtons(){
LinearLayout linLay;
linLay = (LinearLayout) findViewById(R.id.LinLayBut);
RadioGroup radGroup = new RadioGroup(this);
RadioButton radBut = new RadioButton(this);
radGroup.addView(radBut, 0);
radGroup.setText("A button");
}
This is not an efficient way to build dynamic UI. You would be better off defining the optional layout in an XML file and then inflate it when you want to use it:
public void setupRadioButtons() {
final LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout buttons =
(LinearLayout) inflater.inflate(R.layout.LinLayBut, null);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main);
mainLayout.addView(buttons);
}
The above code assumes that the radio group and buttons are defined inside the LinearLayout with id LinLayBut and you main layout id is main.
OK, thanks to unluddite, I got it to work. For those tortured souls following the thread, here's the code. The XML doesn't have a layout around it. And if I don't call the method, the radio group takes no vertical space:
<RadioGroup android:id="#+id/radButGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" />
and here's the method:
public void setupRadioButtons(){
RadioGroup radGroup;
radGroup = (RadioGroup) findViewById(R.id.radButGroup);
RadioButton radBut0 = new RadioButton(this);
radGroup.addView(radBut0, 0); //2nd arg must match order of buttons
radBut0.setText("one Button");
RadioButton radBut1 = new RadioButton(this);
radGroup.addView(radBut1, 1);
radBut1.setText("Two Button");
radBut1.setChecked(true); //which button is set