I'm using Signature Pad and I would like to move the buttons that I add on top of that view using Gravity but nothing happens, I have tried several flags and they all look the same. I also tried to add the signature view to the layout at the end of the method but that didn't change anything either.
The activity:
[Activity(Label = "Authorize Buyin", ScreenOrientation = Android.Content.PM.ScreenOrientation.Landscape)]
public class Sign : Activity
{
LinearLayout layout;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.sign_dialog);
layout = FindViewById<LinearLayout>(Resource.Id.layoutSign);
CreateSignaturePad();
}
private void CreateSignaturePad()
{
var signature = new SignaturePadView(this)
{
StrokeWidth = 3f,
BackgroundColor = Android.Graphics.Color.White,
StrokeColor = Android.Graphics.Color.Black,
};
layout.AddView(signature,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent));
/* Add Clear Button */
Button btnClear = new Button(this) { Text = "Borrar" };
signature.AddView(btnClear);
/* Add Authorize Button */
Button btnAuthorize = new Button(this) { Text = "Authorize" };
btnAuthorize.Gravity = GravityFlags.Center;
signature.AddView(btnAuthorize);
}
}
The layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutSign"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dp">
</LinearLayout>
SignatureView is inherited from RelativeLayout. signature is SignatureView.
This is how I finally solved it:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WrapContent,
RelativeLayout.LayoutParams.WrapContent);
lp.AddRule(LayoutRules.AlignParentBottom);
Button btnAuthorize = new Button(this) { Text = "Authorize" };
btnAuthorize.LayoutParameters = lp;
btnAuthorize.Click += BtnAuthorize_Click;
signature.AddView(btnAuthorize);
Related
I'm a new Android dev student, and I'm trying to create a dynamic layout witch contains a TextView and a button inside the same row.
but I have a little problem.
I set my Button in my Drawables ressources by
button.setBackgroundResource(R.drawable.ic_comment_black_48px);
and now, I cannot change the backgroundcolor behind it.
I have created a newLinearlayout inside my main LinearLayout and have created a new textView and a new Button.
I have put them inside the LinearLayout's child and put it inside the main.
That's work but not the background color behind my button.
is there a way to do that?
my xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
android:id="#+id/historyLayout">
</LinearLayout>
my complete activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
mLinearLayout = findViewById(R.id.historyLayout);
mMoodSaved = new ArrayList(7); // Define the max size of my ArrayList
loadData();
for (int i = 1; i <= 7; i++) {
final TextView textView = new TextView(this);
mLinearLyt = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mLinearLyt.setOrientation(LinearLayout.HORIZONTAL);
textView.setHeight(300);
textView.setWidth(400);
textView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.BLACK);
textView.setTextSize(12);
textView.setText(String.valueOf(i));
mLinearLyt.setBackgroundColor(Color.YELLOW);
mLinearLyt.addView(textView);
mLinearLyt.setLayoutParams(params);
ImageButton button = new ImageButton(this);
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
param2.setMargins(20,50,0,0);
param2.height = 100;
param2.width = 100;
button.setLayoutParams(param2);
button.setBackgroundResource(R.drawable.ic_comment_black_48px);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
soundConfirm();
Toast.makeText(getApplicationContext(), textView.getText(), Toast.LENGTH_LONG).show(); //Display Toast Message
}
});
mLinearLyt.addView(button);
mLinearLayout.addView(mLinearLyt);
}
}
Since this an ImageButton, set
button.setImageResource(R.drawable.ic_comment_black_48px)
instead of setBackgroundResource.
I have horizontal scrollview in my android app with Next and Previous buttons.I want to show the these buttons only when the scollview needs scrolling.ie,width of scrollview content exceeds display width.Also want to hide previous and Next buttons when reaching first and last items respectively.How to to next/previous items when click on these buttons?
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
<Button
android:id="#+id/btnPrevoius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Previous"
android:visibility="gone" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_toLeftOf="#+id/btnNext"
android:layout_toRightOf="#+id/btnPrevoius"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Next"
android:visibility="gone" />
</RelativeLayout>
activity
public class SampleActivity extends Activity {
private static LinearLayout linearLayout;
private static HorizontalScrollView horizontalScrollView;
private static Button btnPrevious;
private static Button btnNext;
private static int displayWidth = 0;
private static int arrowWidth = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
btnPrevious = (Button) findViewById(R.id.btnPrevoius);
btnNext = (Button) findViewById(R.id.btnNext);
for (int i = 0; i < 15; i++) {
Button button = new Button(this);
button.setTag(i);
button.setText("---");
linearLayout.addView(button);
}
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = linearLayout.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
Display display = getWindowManager().getDefaultDisplay();
displayWidth = display.getWidth();
if (linearLayout.getMeasuredWidth() > (displayWidth - 40)) {
btnPrevious.setVisibility(View.VISIBLE);
btnNext.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(listnerLeftArrowButton);
horizontalScrollView.setOnTouchListener(listenerScrollViewTouch);
}
private OnTouchListener listenerScrollViewTouch = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
showHideViews();
return false;
}
};
private OnClickListener listnerLeftArrowButton = new OnClickListener() {
#Override
public void onClick(View v) {
horizontalScrollView.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));
}
};
public static void showHideViews() {
int maxScrollX = horizontalScrollView.getChildAt(0).getMeasuredWidth()- displayWidth;
Log.e("TestProjectActivity", "scroll X = " +horizontalScrollView.getScrollX() );
Log.i("TestProjectActivity", "scroll Width = " +horizontalScrollView.getMeasuredWidth() );
Log.d("TestProjectActivity", "Max scroll X = " + maxScrollX);
if (horizontalScrollView.getScrollX() == 0) {
hideLeftArrow();
} else {
showLeftArrow();
}
if (horizontalScrollView.getScrollX() == maxScrollX) {
showRightArrow();
} else {
//hideRightArrow();
}
}
private static void hideLeftArrow() {
btnPrevious.setVisibility(View.GONE);
}
private static void showLeftArrow() {
btnPrevious.setVisibility(View.VISIBLE);
}
private static void hideRightArrow() {
btnNext.setVisibility(View.GONE);
}
private static void showRightArrow() {
btnNext.setVisibility(View.VISIBLE);
}
}
The 'maxScrollX' value is not correct for me.How to find maximum scrollvalue for this?
Thanks in Advance
This might come a bit late, but for anyone out there that will face this problem I suggest alternative solution(s).
First, use different component than HorizontalScrollView. Here are the options:
OPTION 1: Horizontal ListView - add this class to your project (create a separate package, something like com.yourproject.widgets). Also you'll need to create custom Adapter, see how that's done in this example. I suggest you create separate adapter class (exp. HorizontalListViewAdapter) and put it in already created com.yourproject.widgets package.
add this widget to your layout in the xml (put it between buttons that need to mimic the scrolling behavior) you'll need to add something like:
<com.yourproject.widgets.HorizontalListView
android:id="#+id/hList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
reference this (along with the buttons) in the Activity/Fragment that utilizes the widget
HorizontalListView mHList = (HorizontalListView) findViewById (R.id.hList);
Button bPrevoius = (Button) findViewById (R.id.btnPrevoius);
Button bNext = (Button) findViewById (R.id.btnNext);
add onClickListeners to the Buttons. Use the scrollTo() function predefined in the HorizontalListView widget. As you can see in the code, it takes int dp value to scroll. Add positive values if you want to scroll in right (next), and use negative values if you want to scroll in left (previous):
bPrevoius.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//value 500 is arbitrarily given. if you want to achieve
//element-by-element scroll you should get the width of the
//previous element dynamically or if the elements of the
//list have uniform width just put that value instead
mHList.scrollTo(-500);
//if it's the first/last element you can bPrevoius.setEnabled(false)
}
});
bNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mHList.scrollTo(500);
}
});
OPTION 2: More up to date solution to this issue can be the new widget RecyclerView introduced in Android L (addition of android:scrollbars="vertical" seems that would do the trick; other than that should have conventional ListView behavior). For more info check the official documentation.
devu
Plz have a look at the following links
1) http://android-er.blogspot.in/2012/07/implement-gallery-like.html
2) http://androiddreamers.blogspot.in/2012/09/horizontal-scroll-view-example.html
3)http://code.google.com/p/mobyfactory-uiwidgets-android/
Let me know if u r facing any issues
Thanks
In titanium appcelerator, you can do this using scrollableView
var scrollableView = Ti.UI.createScrollableView({
showPagingControl:true,
scrollingEnabled: true,
top: 360
});
Then, you can run a loop of all images or any content that you have, and add them to this view.
for(loop) {
eval("var view"+i+"=Ti.UI.createView();");
profile_image = Ti.UI.createImageView({
image: result[0]['profile_image'],
left:15,
width:82,
height:104,
top: 0
});
eval("view"+i+".add(profile_image);");
eval("scrollableView.addView(view"+i+");");
}
mywin.add(scrollableView);
I'm trying to get an add button to add another button to the layout, based on the edittext to the left of the button. The point is for a person to list the rooms in their house, and then when they type in each room, a new button is generated so they can click the room, and then start working on the next page.
I had an xml layout all done, and then I realized I'm "programmatically" adding buttons, so I redid the layout programmatically, and then in the switch/case (that's how I do onclicks) for the add button I tried to add a button to the view, but it's getting very tricky. I'd like to have a scrollview below the edittext and add buttons, and as they add all the rooms to their house it eventually is populated with a scrollable list of buttons for their entire home. Is there a way to add buttons programmatically to an xml'd layout. I was thinking you can but everything I'm trying just isn't working.
Thanks for your help everybody, any recommendations you have would be greatly appreciated.
First Edit (in response to Tanuj's solution)
My XML file (not sure if we're going to use this or just use the java):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvAddARoom" />
<EditText
android:id="#+id/etAddARoom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/etAddARoom" />
<Button
android:id="#+id/btnAddARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAdd" />
<TextView
android:id="#+id/tvSelectARoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvSelectARoom" />
<TextView
android:id="#+id/tvNoRooms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvNoRooms" />
<Button
android:id="#+id/btnViewAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnViewAll" />
</LinearLayout>
And the Java. This isn't at all correct, as in the java I'm creating the whole layout instead of using the layout above. Just not sure if I can bridge the two.
package com.bluej.movingbuddy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
//import android.widget.ScrollView;
import android.widget.TextView;
public class EstimatorByRoom extends Activity implements OnClickListener {
String roomName;
EditText etAddARoom;
LinearLayout layout;
LinearLayout.LayoutParams layoutParam;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.estimatorbyroom);
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
//create a layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//create a text view
TextView tvAddARoom = new TextView(this);
tvAddARoom.setText("Add a Room");
tvAddARoom.setLayoutParams(params);
//create an edittext
EditText etAddARoom = new EditText(this);
etAddARoom.setHint("Living Room, Dining Room, etc.");
etAddARoom.setLayoutParams(params);
//create a button
Button btnAddARoom = new Button(this);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
//adds the textview
layout.addView(tvAddARoom);
//add the edittext
layout.addView(etAddARoom);
//add the button
layout.addView(btnAddARoom);
//create the layout param for the layout
LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
this.addContentView(layout, layoutParam);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//this part isn't working!
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
layout.addView(createdButton);
this.addContentView(layout, layoutParam);
//if no rooms make tvnorooms disappear
break;
}
}
}
Try this :
//the layout on which you are working
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);
Try this code:
LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_layout);
l_layout.setOrientation(LinearLayout.VERTICAL); // or HORIZONTAL
Button btn1 = new Button(this);
btn1.setText("Button_text");
l_layout.addView(btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// put code on click operation
}
});
that is a way to create button dynamically and add in Layout.
remember that when you create button programmatically you just use this not Class_name.this
public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {
final int TOP_ID = 3;
final int BOTTOM_ID = 4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create two layouts to hold buttons
LinearLayout top = new LinearLayout(this);
top.setId(TOP_ID);
LinearLayout bottom = new LinearLayout(this);
bottom.setId(BOTTOM_ID);
// create buttons in a loop
for (int i = 0; i < 2; i++) {
Button button = new Button(this);
button.setText("Button " + i);
// R.id won't be generated for us, so we need to create one
button.setId(i);
// add our event handler (less memory than an anonymous inner class)
button.setOnClickListener(this);
// add generated button to view
if (i == 0) {
top.addView(button);
}
else {
bottom.addView(button);
}
}
// add generated layouts to root layout view
LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
root.addView(top);
root.addView(bottom);
}
#Override
public void onClick(View v) {
// show a message with the button's ID
Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
toast.show();
// get the parent layout and remove the clicked button
LinearLayout parentLayout = (LinearLayout)v.getParent();
parentLayout.removeView(v);
}
}
Each button needs to have an onclicklistener to tell it what to do. this can be added to your java code under where you state your button.
Button createdButton = new Button(this);
createdButton.setOnClickListener(new OnClickListener()
{
code you want implemented
}
I would add an id to your LinearLayout in xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/llContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
And then change your onClick to this:
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddARoom:
//add a room
//Find you parent layout which we'll be adding your button to:
LinearLayout layout = (LinearLayout) findViewById(R.id.llContainer);
roomName = etAddARoom.getText().toString();
Button createdButton = new Button(this);
createdButton.setText(roomName);
createdButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
layout.addView(createdButton);
//if no rooms make tvnorooms disappear
break;
}
}
I want to give ID to some views (textview ,imageview etc) in a layout that is programmetically created.
So what is the best way to set ID.
You create an ids.xml file and place all your required ids in it as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="layout1" />
<item type="id" name="layout2" />
<item type="id" name="layout3" />
</resources>
Now for your dynamically created layouts or views you can use these ids as below
new_layout1.setId(R.id.layout1);
new_view2.setId(R.id.layout2);
new_layout3.setId(R.id.layout3);
I hope it may help you.
Google finally realized the need of generating unique IDs for programmatically created views...
From API level 17 and above, one can use View.generateViewId() like this:
view.setId(View.generateViewId());
For apps targeting API level 16 or lower, use ViewCompat.generateViewId() instead:
view.setId(ViewCompat.generateViewId());
create folder res/values/ids.xmland
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="refresh" type="id"/>
<item name="settings" type="id"/>
</resources>
in Activity class call like this
ImageView refreshImg = new ImageView(activity);
ImageView settingsImg = new ImageView(activity);
refreshImg.setId(R.id.refresh);
settingsImg .setId(R.id.settings);
This wont work:
layout.setId(100);
But, this will:
int id=100;
layout.setId(id);
also, this one too (credit: Aaron Dougherty):
layout.setId(100+1);
For compatibility purposes use: ViewCompat.generateViewId()
If you are putting a group of components repeatedly into a layout programmatically like below:
<LinearLayout>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
...
</LinearLayout>
then,you can use for loop and give ids accordingly:
for(int i=0;i<totalGroups;i++)
{
ImageView img;
TextView tv;
Button b;
... // set other properties of above components
img.setId(i);
tv.setId(i);
b.setId(i);
... //handle all events on these components here only
... //add all components to your main layout
}
Or if just one group of component you want to add,you can use any integer number which is large and don't conflict with other component's ids in Resources.It won't be much conflicting.
I went about it in a different way.
Created my own R.id HashMap.
Than used the value for the view.setID() part.
String is the id, Integer its value
Private HashMap<String, Integer> idMap= new HashMap<String, Integer>();
private int getRandomId(){
boolean notInGeneralResourses = false;
boolean foundInIdMap = false;
String packageName = mainActivity.getPackageName();
Random rnd = new Random();
String name ="";
//Repaet loop in case random number already exists
while(true) {
// Step 1 - generate a random id
int generated_id = rnd.nextInt(999999);
// Step 2 - Check R.id
try{
name = mainActivity.getResources().getResourceName(generated_id);
}catch(Exception e){
name = null;
}
notInGeneralResourses = false;
if (name == null || !name.startsWith(packageName)) {
notInGeneralResourses = true;
}else{
notInGeneralResourses = false;
localLog("Found in R.id list.");
}
// Step 3 - Check in id HashMap
if(notInGeneralResourses){
List<Integer> valueList = new ArrayList<Integer>(idMap.values());
foundInIdMap = false;
for (Integer value : valueList) {
if (generated_id == value) {
foundInIdMap = true;
localLog("Found in idMAp.");
}
}
}
// Step 4 - Return ID, or loop again.
if (!foundInIdMap) {
localLog("ID clear for use. "+generated_id);
return generated_id;
}
}
}
and to set:
String idName = "someName";
int generated_R_id = getRandomId();
idMap.put(idName,generated_R_id);
someView.setId(idMap.get(idName));
Now, at any point you can just:
ImageView test = (ImageView)
mainActivity.findViewById(idMap.get("somName"));
and to test it -
test.setImageResource(R.drawable.differentPic);
P.S. I've written it like this for ease of explain.
Obviously it can be written better andmore compact.
Try this code!
This should help give an idea.
activity_prac_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">
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/display_txt"
android:textStyle="bold"
android:textSize="18sp"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<GridLayout
android:id="#+id/my_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="4">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear_view">
<Button
android:text="#string/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_btn"
android:layout_gravity="center_horizontal"/>
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_txt"
android:textSize="18sp"
/>
</LinearLayout>
</GridLayout>
</LinearLayout>
here's the rest of code
public class AnotherActivity extends AppCompatActivity {
private int count = 1;
List<Integer> gridArray;
private TextView myDisplayText;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gridArray = new ArrayList<>();
gridArray.add(Integer.valueOf(1));
setContentView(R.layout.activity_prac_main);
findViews();
}
private void findViews(){
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.setColumnCount(4);
LinearLayout linearLayout = (LinearLayout) gridLayout.findViewById(R.id.linear_view);
linearLayout.setTag("1");
Button myButton = (Button) linearLayout.findViewById(R.id.my_btn);
myButton.setTag("1");
TextView myText = (TextView) linearLayout.findViewById(R.id.my_txt);
myText.setText("1");
myDisplayText = (TextView) findViewById(R.id.display_txt);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
}
private void createView(){
LinearLayout ll = new LinearLayout(this);
ll.setId(Integer.valueOf(R.id.new_view_id));
ll.setTag(String.valueOf(count+1));
Button newBtn = createButton();
newBtn.setId(Integer.valueOf(R.id.new_btn_id));
newBtn.setTag(String.valueOf(count+1));
TextView txtView = createText();
txtView.setId(Integer.valueOf(R.id.new_txt_id));
txtView.setTag(String.valueOf(count+1));
txtView.setText(String.valueOf(count+1));
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
ll.addView(newBtn);
ll.addView(txtView);
ll.setOrientation(LinearLayout.VERTICAL);
gridLayout.addView(ll);
count++;
}
private Button createButton(){
Button myBtn = new Button(this);
myBtn.setText(R.string.button_send);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
return myBtn;
}
public void dialogBox() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GRID IS FULL!");
alertDialogBuilder.setPositiveButton("DELETE",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.removeAllViews();
count = 0;
createView();
}
});
alertDialogBuilder.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private TextView createText(){
TextView myTxt = new TextView(this);
myTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
return myTxt;
}
}
As you can see ids were created in res -> values -> ids file.
when creating views dynamically id is the same for the views.
Each TextView share same id. Each Button share same id. each layout share same id.
Ids are only important to access the contents of views.
However the Tag is what makes each view unique to each other.
Hope this helps you out!
All you need to do is call ViewCompat.generateViewId()
For Example:
val textView = TextView(this)
textView.text = "Hello World"
textView.setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
textView.id = ViewCompat.generateViewId()
You can define your Ids as resources and then use setId() of the view to set it.
In a xml file, define the ID's like:
<resources>
<item type="id">your id name</item>
</resources>
then, use in the java file as..
layout.setId(R.id.<your id name>)
Looking for an example of how to dynamically add controls from the activity.
Inside an activity, lets call it "Activity2.cs", dynamically add a variable number of buttons to "MyView.axml".
I'm looking for code like below (except code that actually works):
string[] textArray = new string[] { "button1", "button2", "button3", "button4" };
int counter= 3;
for (int i = 0; i < length; i++)
{
var mytest = new button(this);
mytest.Text = textArray[i];
mytest.id= textArray[i];
View(MyView.axml).add(mytest);
}
The result would be that four buttons are added at the bottom of the view. I can find examples for how to dynamically add controls in Android, but not when using Mono for Android (ie in Visual Studio).
Let's say your layout file looks like this (Main.axml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Buttons">
</LinearLayout>
Then in your activity you can add Button objects to the layout like this:
[Activity(Label = "Buttons", MainLauncher = true, Icon = "#drawable/icon")]
public class ButtonActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var buttons = FindViewById<LinearLayout>(Resource.Id.Buttons);
for (int i = 1; i <= 4; i++)
{
var button = new Button(this);
button.Text = "Button " + i;
button.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.WrapContent);
buttons.AddView(button);
}
}
}