In one of the activity of my app, I have a button where I want to display an image with each button click. For example:
By clicking the button of my activity, an image appears on screen as shown.
The second and following clicks on the button will results in the new image to append accordingly.
I would like to have some suggestion on how do I achieve this.
I made something similar to this but with TextView. Basically I did this:
XML:
For my case I made TableLayout Ex:
<TableLayout
android:id="#+id/existedTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin_standard">
<TableRow>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/number_text"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large" />
</TableRow>
</TableLayout>
Activity
Note: Change it to ImageView for your case
/* //Get the TableLayout. Ex:
private TableLayout existedTableLayout = findViewById(R.id.existedTableLayout);
*/
/* Make onClickListerner to call below function */
private void addTableRowDynamically() {
//Make new Row
TableRow newRow= new TableRow(this);
TextView newNoTextView = new TextView(this);
//some TextView method, do your research about ImageView
newNoTextView.setLayoutParams(new TableRow.LayoutParams(0,ViewGroup.LayoutParams.WRAP_CONTENT, 1));
newNoTextView.setText("this is text");
newNoTextView.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
// Add the TextView to the newRow
newRow.addView(newNoTextView);
// Add the newRow which contain the TextView to the TableLayout, below
existedTableLayout.addView(newRow, existedTableLayout.getChildCount());
}
Add a vertical LineaLayout and add views dynamically:
private void createViews() {
for (int i = 0; i < numberOfViews; i++) {
view = new ImageView(context);
int width = 300;
int height = 50;
view.setPadding(18, 10, 0, 0);
view.setLayoutParams(new LinearLayout.LayoutParams(width, height));
view.setId(i);
view.setGravity(Gravity.CENTER_VERTICAL);
view.setBackgroundColor(Color.parseColor("someColor"));
viewList.add(view);
}
}
Rect rectf = new Rect();
for (ImageView view : viewList) {
view.getGlobalVisibleRect(rectf);
coordinates.add(rectf.bottom);
}
Related
i would like to create a TextView with a colored background and space between each line, link this:
I'm trying with SpannableString but i can't create transparent space between lines, any idea?
Thanks and guys sorry for my BAD english.
Try using lineSpacingExtra and lineSpacingMultiplier in your XML file.
If I am not taking wrong you want to add a transparent new line in your TextView ?
This can't be possible with single TextView as SpannableString will only effect the content of TextView and background of Textview is different from content of TextView.
If you have to achieve this then you have to provide custom implementation for TextView which will draw a transparent background in onDraw method for your custom view when in text content it find new line.
Or other option is to render a new textview for each line of text.
Hi it should be done using add textview dynemically in layout and at that time you have to set properties of textview.You can do this like
TvEx.java
public class TvEx extends Activity {
LinearLayout llMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tv_ex);
llMain = (LinearLayout) findViewById(R.id.llmainTvEx);
final int N = 10; // total number of textviews to add
final TextView[] myTextViews = new TextView[N]; // create an empty
// array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(100, 20, 0, 0); // Set margins here
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
rowTextView.setBackgroundColor(Color.WHITE);
rowTextView.setLayoutParams(buttonLayoutParams);
// add the textview to the linearlayout
llMain.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
}
}
tv_ex.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/llmainTvEx"
android:layout_height="match_parent"
android:background="#A75653"
android:orientation="vertical"></LinearLayout>
I would like to inflate imagebuttons programmatically to a linearlayoutm, coded as follows:
Code:
public void set_keyboard_words(int row, int start, int end)
{
for (int p = start; p <= end; p++)
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(btn_ball_sq,btn_ball_sq);
params.setMargins(0, 0, 0, 0);
keyboard_btn = new ImageButton(this);
keyboard_btn.setId(p);
final int id_ = keyboard_btn.getId();
keyboard_btn.setImageResource(BUTTON_IMG[p-1]);
keyboard_btn.setBackgroundResource(R.drawable.btn_blue_selector);
keyboard_btn.setScaleType(ImageView.ScaleType.FIT_XY);
keyRow1.addView(keyboard_btn, params);
keyboard_btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
button_action(id_);
}
});
}
}
Xml:
<LinearLayout
android:id="#+id/keyRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:splitMotionEvents="false" >
</LinearLayout>
Background:
The imagebuttons are some balls.
The imagebuttons could be inflated to the linearlayout keyRow1.
However, I do not know how to set the image resources to the imagebuttons correctly. The balls inflated are so small instead of fitting to XY of the buttons.
Screenshot as follows:
If image set as keyboard_btn.setImageResource(BUTTON_IMG[p-1]); (with blue backgrounds as BackgroundResource for seeing the actual size of button), the balls are very small
If image set as keyboard_btn.setBackgroundResource(BUTTON_IMG[p-1]);, the size is now proper but the actual backgroundResource cannot be set anymore
Question:
I would like to use the method of setImageResource for the imagebuttons as the button background would later be changed to other background image upon pressed.
How could I set the imagebutton's image using setImageResource but with size of balls similar to the 2nd screenshot??
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
keyboard_btn = new ImageButton(this);
keyboard_btn.setId(p);
final int id_ = keyboard_btn.getId();
keyboard_btn.setImageResource(BUTTON_IMG[p-1]);
keyboard_btn.setBackgroundResource(R.drawable.btn_blue_selector);
keyboard_btn.setLayoutParams(params);
Just try the above code, if the image doesn't shrink then you need to optimize the image based on the width you get for each button from screen width.
I'm creating a chat application, on launch it displays the twenty most recent messages in a conversation. When you scroll to the top you can press a button to display earlier messages. Pretty typical. The only problem is, I want the UI elements to maintain their position after pressing the button. At the moment they shift. I've created a stripped out version of the problem I'm having.
Before pressing the button
After pressing the button
As you might have guessed, I would like it so that after I press the button the TextView with the label 51 (TextView-51) appears as if it hasn't moved. My original plan was to get the position of TextVie-51 before the button press, and then after the button press, and set the ScrollView's Y position. However that approach doesn't work because the at the time I was checking the View hadn't inflated yet.
Here's the layout xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/TestScroller">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/mainContainer" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TestButton"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:onClick="insertMore"
android:text="Get Earlier Messages" />
</RelativeLayout>
</ScrollView>
Here's the code for the activity.
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
lastId = R.id.TestButton;
firstId = -1;
RelativeLayout rl = (RelativeLayout)findViewById(R.id.mainContainer);
//1. Create fifty TextViews and put them under the button.
for (int i = 51; i <= 100; i++)
{
TextView tv = new TextView(this);
tv.setText(Integer.toString(i));
tv.setId(i + 100);
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
params.addRule(RelativeLayout.BELOW, lastId);
tv.setLayoutParams(params);
lastId = tv.getId();
if (firstId == -1)
firstId = tv.getId();
rl.addView(tv);
}
}
public void insertMore(View view)
{
//Create fifty more TextViews and insert them between the button and
//the already created textviews.
RelativeLayout rl = (RelativeLayout)findViewById(R.id.mainContainer);
lastId = R.id.TestButton;
for (int i = 0; i <= 50; i++)
{
TextView tv = new TextView(this);
tv.setText(Integer.toString(i));
tv.setId(i + 100);
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
params.addRule(RelativeLayout.BELOW, lastId);
tv.setLayoutParams(params);
lastId = tv.getId();
rl.addView(tv);
}
//Now make sure the textview with the label 51 under it is underneath the last
//view we just added.
TextView tv = (TextView)findViewById(firstId);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)tv.getLayoutParams();
params.addRule(RelativeLayout.BELOW, lastId);
tv.setLayoutParams(params);
//Remove the button
Button button = (Button)findViewById(R.id.TestButton);
rl.removeView(button);
}
Based on your first idea which was to scroll to the bottom of the list after adding textviews, did you try to call requestLayout() to force layout update :
public void insertMore(View view)
{
// Create and add your 50 views
...
// force Update layout
rl.requestLayout();
scrollView.post(new Runnable() {
#Override
public void run() {
// Scroll to scrollviews bottom
scrollView.scrollTo(0, scrollView.getBottom());
}
});
}
I have a TableLayout where I add dynamically TableRows. In each TableRow, I add a Button.
I just would like to add some space between my columns (which are my buttons) but I can't figure out how...
I've tried to change all the possible margins but it doesn't work :(
So maybe I made a mistake in my code where I inflate them from XML files:
private void createButtons(final CategoryBean parentCategory) {
final List<CategoryBean> categoryList = parentCategory.getCategoryList();
title.setText(parentCategory.getTitle());
// TODO à revoir
int i = 0;
TableRow tr = null;
Set<TableRow> trList = new LinkedHashSet<TableRow>();
for (final CategoryBean category : categoryList) {
TextView button = (TextView) inflater.inflate(R.layout.button_table_row_category, null);
button.setText(category.getTitle());
if (i % 2 == 0) {
tr = (TableRow) inflater.inflate(R.layout.table_row_category, null);
tr.addView(button);
} else {
tr.addView(button);
}
trList.add(tr);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CategoryBean firstChild = category.getCategoryList() != null && !category.getCategoryList().isEmpty() ? category
.getCategoryList().get(0) : null;
if (firstChild != null && firstChild instanceof QuestionsBean) {
Intent intent = new Intent(CategoryActivity.this, QuestionsActivity.class);
intent.putExtra(MainActivity.CATEGORY, category);
startActivityForResult(intent, VisiteActivity.QUESTION_LIST_RETURN_CODE);
} else {
Intent intent = new Intent(CategoryActivity.this, CategoryActivity.class);
intent.putExtra(MainActivity.CATEGORY, category);
startActivityForResult(intent, VisiteActivity.CATEGORY_RETURN_CODE);
}
}
});
i++;
}
for (TableRow tableRow : trList) {
categoryLaout.addView(tableRow);
}
}
My button_table_row_category.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/buttonTableRowCategory"
style="#style/ButtonsTableRowCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/validate" />
My table_row_category.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tableRowCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="100dp"
android:gravity="center"
android:padding="5dp" >
</TableRow>
Thank you for your help.
In the case of a TableLayout, Buttons themselves are the columns. That means you have to advise the Buttons to keep some space inbetween. You can do this by using layout parameters. They are much easier to set in XML, but it also works programmatically. It's important that you always use the LayoutParam class of the parent layout of the element where you apply it - in this case the parent is a TableRow:
// Within createButtons():
android.widget.TableRow.LayoutParams p = new android.widget.TableRow.LayoutParams();
p.rightMargin = DisplayHelper.dpToPixel(10, getContext()); // right-margin = 10dp
button.setLayoutParams(p);
// DisplayHelper:
private static Float scale;
public static int dpToPixel(int dp, Context context) {
if (scale == null)
scale = context.getResources().getDisplayMetrics().density;
return (int) ((float) dp * scale);
}
Most dimension attributes in Android take pixels if you set them programmatically - therefore you should use something like my dpToPixel() method. Please, don't EVER use pixel values in Android! You will regret it later on.
If you don't want the rightmost button to have this margin, just check with an IF and don't add the LayoutParam on it.
Solution in XML:
To avoid the LayoutInflater erasing your XML-defined attributes, do this while inflating (taken from Layout params of loaded view are ignored):
View view = inflater.inflate( R.layout.item /* resource id */,
MyView.this /* parent */,
false /*attachToRoot*/);
Alternative: Use a GridView like so: Android: Simple GridView that displays text in the grids
Add Padding Right for a component in the table row component
<TableRow
android:id="#+id/tableRow1">
<TextView
android:id="#+id/textView1"
android:paddingRight="20dp" />
</TableRow>
Try android:layout_marginRight="6dp" this worked for me.
Try Using the setColumnStretchable function of the TableLayout. Give it a columnn index and set its stretchable property to true.
Eg. If you have 3 columns.
TableLayout tblLayout;
tblLayout.setColumnStretchable(0, true);
tblLayout.setColumnStretchable(1, true);
tblLayout.setColumnStretchable(2, true);
The above will give you equal spacing between all 3 columns of the tableLayout.
I have lists of LinearLayouts with horizontal orientation each one containing two textviews added dynamically.
This LinearLayout is finally wrapped into master LinearLayout.
I want the second textview of each linear layout to be right aligned progrmatically. How can I do this dynamically.
Here's sample code:
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);
There is android:layout_alignParentRight attribute. But how to set this dynamically in this case. Any clue?
The android:layout_alignParentRight can only be applied to a view if its parent is a RelativeLayout. Change your container to that, and the 2 sub-views can use any of the layout_alignParent* attributes.
If you can't do this programatically (which I can't see how to do quickly), then you could always define your inner layout in xml (where you can easily get the layout correct) and inflate manually via:
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View l = vi.inflate(R.layout.inner_relative_layout, null);
TextView leftTextView = (TextView) l.findViewById(R.id.left_text);
leftTextView.setText("left");
// ... fill in right text too
placeHolderLinearLayout.addView(l);
Edit: added layout definition
Use a layout like this, and inflate it in the code as above:
<RelativeLayout android:id="#+id/inner_relative_layout" android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView android:id="#+id/left_text" android_alignParentLeft="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="#+id/right_text" android_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>
You will be creating multiple of these layouts for each item you're adding to your list.
this one is woking and simple answer::
public class MainActivity extends Activity {
TextView text[];
TextView texto[];
CheckBox check[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.layout);
text = new TextView[5];
texto = new TextView[5];
check = new CheckBox[5];
for (int i = 0; i < 5; i++) {
text[i] = new TextView(this);
text[i].setText("First one is::" + i);
texto[i] = new TextView(this);
texto[i].setText("sennd one ibs::" + i);
check[i] = new CheckBox(this);
((ViewGroup) view).addView(check[i]);
((ViewGroup) view).addView(text[i]);
((ViewGroup) view).addView(texto[i]);
}
}
}
Please try below
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
txt1.setGravity(Gravity.LEFT);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
txt1.setGravity(Gravity.RIGHT);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);