LinearLayout linContact = (LinearLayout) mView.findViewById(R.id.linContacts);
LinearLayout.LayoutParams leftGravityparas = new LinearLayout.LayoutParams(0,LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams rightGravityParams = new LinearLayout.LayoutParams(30, 30);
for (int i = 0; i < contactList.size(); i++) {
final ClsAdviserData contact = .contactList.get(i);
if (contact.isSelected()) {
linearLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams linMainparam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(linMainparam);
linMainparam.setMargins(0, 10, 0, 0);
leftGravityparas.gravity = Gravity.LEFT;
leftGravityparas.weight = 0.9f;
TextView txtContact = new TextView(getActivity());
txtContact.setTextSize(16);
// txtContact.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
txtContact.setLayoutParams(leftGravityparas);
txtContact.setId(i);
leftGravityparas.setMargins(0, 10, 0, 0);
txtContact.setPadding(20, 10, 10, 10);
txtContact.setText(contact.getName());
linearLayout.addView(txtContact, leftGravityparas);
rightGravityParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
rightGravityParams.weight = 0.1f;
final ImageView imgDelContact = new ImageView(getActivity());
imgDelContact.setLayoutParams(rightGravityParams);
imgDelContact.setTag(i);
imgDelContact.setClickable(true);
imgDelContact.setOnClickListener(this);
imgDelContact.setImageResource(R.drawable.ic_close_grey);
linearLayout.addView(imgDelContact, rightGravityParams);
// linContact.setTag(i);
linContact.addView(linearLayout);
imgDelContact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Toast ==>" + contact.getName() + v.getTag(), Toast.LENGTH_SHORT).show();
// linContact.removeViewAt((Integer) v.getTag());
linearLayout.setVisibility(View.GONE);
// lin.removeViewAt((Integer)v.getTag());
}
});
}
}
I wrote the above code to create the textfields and buttons dynamically; But now I need to remove 2 textfields and a button when the button is clicked. How do I do that?
adding -
After initializing add subview using addView() method declared in LinearLayout
linearLayout.addView(txtContact);
linearLayout.addView(imgDelContact);
Hide -
To hide View ,so that you can get it again whenever required
imgDelContact.setVisibility(View.GONE);
txtContact.setVisibility(View.GONE);
Remove -
Or you can remove if you don't want to use it again.
linearLayout.removeView(txtContact);
linearLayout.removeView(imgDelContact);
To remove any view you can use
aLinearLayout.removeView(view)// to remove particular view
aLinearLayout.removeViewAt(position);// to remove view from particular position
If you are dynamically creating views and you just need to remove all the views just use
aLinearLayout.removeAllViews();
This will clear the layout.
Related
I'm trying to implement an scrollable horizontal Linearlayout inside scrollview in a method dynamically , but the view (LinearLayout) does not scroll!
This method get some result from server and then create the view dynamically. "layout_services" is an vertical LinearLayout which is implemented inside xml file.
Voila the code :
for (ServiceResult serviceResult : response.getResult()) {
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewParams.setMargins(15, 15, 15, 15);
textViewParams.gravity = Gravity.RIGHT;
TextView textView = new TextView(getActivity());
textView.setPadding(5, 5, 5, 5);
textView.setText(serviceResult.getCategory());
textView.setLayoutParams(textViewParams);
textView.setTextColor(Color.WHITE);
textView.setBackgroundColor(Color.LTGRAY);
if (!serviceResult.getServices().isEmpty()) {
layout_services.addView(textView);
LinearLayout.LayoutParams scrollLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ScrollView scrollView = new ScrollView(getActivity());
scrollView.setLayoutParams(scrollLayoutParams);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setPadding(5, 5, 5, 5);
LinearLayout.LayoutParams horizontalLayoutParams =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
horizontalLayoutParams.gravity = Gravity.RIGHT;
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(horizontalLayoutParams);
scrollView.addView(linearLayout);
for (int i = 0; i < serviceResult.getServices().size(); i++) {
int finalI = i;
Button btn = new Button(getActivity());
btn.setText(serviceResult.getServices().get(finalI).getName());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, 200);
params.setMargins(15, 15, 15, 15);
params.gravity = Gravity.LEFT;
btn.setLayoutParams(params);
btn.setTextColor(Color.BLACK);
btn.setOnClickListener(view -> {
});
linearLayout.addView(btn);
}
layout_services.addView(scrollView);
}
}
Use HorizontalScrollView instead of ScrollView as parent of Linear Layout that you want to scroll horizontally
You can try nested scroll view.
Read the documentation here : Nested Scroll View
Which will be the better way to create a Vertical Lineal layout with four or more buttons in each row
The problems I have face are the following:
Setting the id of each button manually will result in a lot of repetitive code, more resources usage and you will have to change everyone to add a feature or change something (I think using an adapter will be the most efficient way, but...)
From what I know using a CustomAdapter don't help you set a unique ID to the buttons
Can you use an adapter to set a different id for each button dipending of the row?
Example:
second button of third row: r3b2
fifth button of first row: r1b5
Thanks.
You can create the buttons programmatically in our Activity class like this
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout); // the layout in which u want to display the buttons
layout.setOrientation(LinearLayout.VERTICAL);
int count = 1;
for (int i = 0; i < 5; i++) { // i = row count
LinearLayout row = new LinearLayout(getActivity());
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
for (int j = 0; j < 7; j++) { // j = column count (create 7 buttons in each row)
int id = count;
final Button btnTag = new Button(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
params.weight = 1;
params.gravity = Gravity.CENTER;
btnTag.setLayoutParams(params);
btnTag.setBackgroundColor(Color.parseColor("#ffffff"));
String dateSuffix = count + getDayNumberSuffix(count);
btnTag.setTag(dateSuffix);
btnTag.setId(id);
btnTag.setText(count + "");
btnTag.setTextSize(12.0f);
btnTag.setOnClickListener(getOnClickDoSomething(btnTag, count));
row.addView(btnTag);
count++;
}
layout.addView(row);
}
View.OnClickListener getOnClickDoSomething(final Button btnTag, final int count) {
return new View.OnClickListener() {
public void onClick(View v) {
// here you can do what u want to do on button click
}
}
I am trying to create a table with 2 textviews, edittextview and a button programmatically. My button height is not equal to rest of the elements.
I have tried removing padding and margin but the issue persisted.
Can anyone point out the error or provide a workaround to this.
code is as follows
public void populateItems()
{
// TODO : create uniform table row cells
TableLayout tl = (TableLayout)findViewById(R.id.placeOrderTable);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER_HORIZONTAL;
lp.bottomMargin=5;
LayoutParams lpTextView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
lpTextView.weight=1;
lpTextView.width=0;
lpTextView.bottomMargin=1;
LayoutParams lpEditTextView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lpEditTextView.weight=1;
lpEditTextView.width=0;
// lpEditTextView.
//lpEditTextView.
lpEditTextView.gravity=Gravity.CENTER_HORIZONTAL;
for(final HashMap<String,String> hm:mTodayItemsHashMap)
{
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(lp);
TextView tvItemName = new TextView(getApplicationContext());
tvItemName.setLayoutParams(lpTextView);
tvItemName.setBackgroundResource(R.drawable.border_edittext);
tvItemName.setText(hm.get("item_name").toUpperCase());
tvItemName.setEms(10);
tvItemName.setTextColor(Color.BLACK);
tvItemName.setGravity(Gravity.CENTER);
// evItemName.setHint(getString(R.string.item_name));
TextView tvItemPrice = new TextView(getApplicationContext());
tvItemPrice.setLayoutParams(lpTextView);
tvItemPrice.setBackgroundResource(R.drawable.border_edittext);
tvItemPrice.setTextColor(Color.BLACK);
tvItemPrice.setText(hm.get("item_price").toUpperCase());
tvItemPrice.setGravity(Gravity.CENTER);
tvItemPrice.setEms(10);
// evItemPrice.setHint(getString(R.string.item_price));
final EditText evItemQty = new EditText(getApplicationContext());
evItemQty.setLayoutParams(lpTextView);
evItemQty.setInputType(InputType.TYPE_CLASS_NUMBER);
evItemQty.setBackgroundResource(R.drawable.border_edittext);
evItemQty.setTextColor(Color.BLACK);
evItemQty.setGravity(Gravity.CENTER);
evItemQty.setEms(10);
evItemQty.setFilters(new InputFilter[]{ new InputFilterMinMax("1", hm.get("max_qty"))});
// evItemQty.setL
evItemQty.setHint(getString(R.string.max_orders));
Button btnAddToCart=new Button(getApplicationContext());
btnAddToCart.setLayoutParams(lpTextView);
btnAddToCart.setText("Add to Cart");
btnAddToCart.setPadding(0, 0, 0, 0);
// btnAddToCart.setLayoutParams(params);
// btnAddToCart.setBackgroundResource(R.drawable.border_edittext);
btnAddToCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// mCart.
item=new Item();
item.setName(hm.get("item_name"));
item.setPrice(hm.get("item_price"));
String temp=evItemQty.getText().toString();
try{
Integer.parseInt(temp);
}
catch(NumberFormatException nfe){
Toast.makeText(getApplicationContext(), "Please specify quantity",Toast.LENGTH_LONG);
return;
}
item.setQty(evItemQty.getText().toString());
if(mCart==null)
mCart=new Cart();
mCart.add(item);
}
});
tr.addView(tvItemName);
tr.addView(tvItemPrice);
tr.addView(evItemQty);
tr.addView(btnAddToCart);
tl.addView(tr,tl.getChildCount()-1, tl.getLayoutParams());
}
}
You will probably want to override the background of the button. You'll get something like this:
This of course means you will not have the curved edges anymore. This can be fixed
as explained in this answer
I have a ScrollView and I want to insert a user specified number of HorizontalScrollViews. So what user says he wants to have a matrix of 5x5 elements, I want to insert 5 HorizontalScrollViews with 5 EditText objects each. My program adds the first line just as it's supposed to, but the rest not.
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(par2);
HorizontalScrollView row = new HorizontalScrollView(this);
row.setLayoutParams(par1);
row.addView(ll);
for (int j = 0; j < number; j++) {
EditText txt = new EditText(this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setHint(i+","+j);
ll.addView(txt);
}
latout_in_scrollview.addView(row);
}
Any ideas why? Thanks!
EDIT:
The 1:1 code im using
LinearLayout dijkstra_rows;
FrameLayout.LayoutParams par1 = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams par2 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_dijkstra);
dijkstra_rows = (LinearLayout) findViewById(R.id.dijkstra_rows);
Bundle extras = getIntent().getExtras();
number = extras.getInt("vertexes");
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(par2);
HorizontalScrollView row = new HorizontalScrollView(this);
row.setLayoutParams(par1);
row.addView(ll);
for (int j = 0; j < number; j++) {
EditText txt = new EditText(this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setHint(i+","+j);
ll.addView(txt);
}
dijkstra_rows.addView(row);
}
}
ScrollView can contain only one childView. You can put any layout as per your requirement. I generally use Relative Layout...
Then add views dynamically to relative layout
viewLayout = (ViewGroup) mView.findViewById(R.id.YOUR_RELATIVE_LAYOUT_ID);
View lastCard = viewLayout.getChildAt(viewLayout.getChildCount() - 1);
// INFLATE YOUR NEW VIEW YOU WANT TO ADD
CardView cardView = (CardView)
LayoutInflater.from(getContext()).inflate(R.layout.card_nearest_stop, null);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//Set id to view
int id = 125;
if (lastCard != null) {
params.addRule(RelativeLayout.BELOW, lastCard.getId());
id = lastCard.getId() + 125;
}
cardView.setLayoutParams(params);
cardView.setId(id);
viewLayout.addView(cardView);
ScrollView is a single element container.
A ScrollView is a FrameLayout, meaning you should place one child in
it containing the entire contents to scroll; this child may itself be
a layout manager with a complex hierarchy of objects. A child that is
often used is a LinearLayout in a vertical orientation, presenting a
vertical array of top-level items that the user can scroll through.
You are adding multiple LinearLayouts here
for (int i = 0; i < number; i++) {
LinearLayout ll = new LinearLayout(this);
.
.
}
You should have only one out of this loop. Then add this one to your scrollView, in Loop you can add muliple HorizontolScrollViews to this LinearLayout
I use this code to dynamically print the vaules from my database with a buttonClick-event.
The buttonClick-event to delete the database entry is present inside the a loop.
Here my code:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout3);
final DatabaseHandler dbpin = new DatabaseHandler(this);
// Log.d("Reading: ", "Reading all tasks..");
List<Detail> detail1 = dbpin.getAllDetail();
Button[] button=new Button[1000];
for (Detail cn : detail1) {
String log = cn.getTitle();
final int i = cn.getID();
button[i] = new Button(this);
button[i].setText("Delete");
button[i].setTextSize(10);
button[i].setId(2000 + i);
int width = 80;
int height = 60;
TextView textview = new TextView(this);
textview.setText(log);
textview.setWidth(200);
textview.setTextSize(20);
textview.setPadding( 0, 10, 0, 0);
textview.setId(2000 + i);
if (i == 0) {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textview.setLayoutParams(rlp2);
rl.addView(textview);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
width, height);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
button[i].setLayoutParams(rlp1);
rl.addView(button[i]);
} else {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlp2.addRule(RelativeLayout.BELOW, button[i].getId() - 1);
textview.setLayoutParams(rlp2);
rl.addView(textview);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
width, height);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlp1.addRule(RelativeLayout.BELOW, button[i].getId() - 1);
button[i].setLayoutParams(rlp1);
rl.addView(button[i]);
}
button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), details.class);
Detail detail = new Detail();
detail.setID(i);
dbpin.deleteDetail(detail);
startActivityForResult(myIntent, 1);
}
});
}
Following the database handler code is, to retrieve all details from database using a loop:
// Getting All detail
public List<Detail> getAllDetail() {
List<Detail> detailList = new ArrayList<Detail>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DETAIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Detail detail = new Detail();
detail.setID(Integer.parseInt(cursor.getString(0)));
detail.setTitle(cursor.getString(1));
detail.setDetail(cursor.getString(2));
// Adding contact to list
detailList.add(detail);
} while (cursor.moveToNext());
}
// return contact list
return detailList;
}
// Deleting single detail
public void deleteDetail(Detail detail) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DETAIL, KEY_DETID + " = ?",
new String[] { String.valueOf(detail.getID()) });
db.close();
}
At first the layout is normal. Deleting first or the last data row doesn't cause any change, but if a row in the middle is deleted, then the layout overlaps each other.
Please give me suggestions to clear this logical error.
Ok I have understand your problem. Problem is that you are using relative layout as your parent layout in which you are adding all your child relative layouts. Now if you delete your first relative layout then it automatically align with its parent so there will be no problem.
If you delete last relative layout then also not problem occurs.
Now you have align all your relative layout form their above layout so if you delete above one it automatically aligns to its parent.
Solution is simple. Use your parent layout as linear layout so that you dont need to align relative layouts with their above layout. It will automatically arrange in a linear way....
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout3); convert this layout in linearlayout in your xml file.
This the code which can help you:
LinearLayout lp = (LinearLayout) findViewById(R.id.LinearLayout1);
// for loop start from here
RelativeLayout rl = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams lp_btn = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp_btn.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
Button temp_button = new Button(getApplicationContext());
temp_button.setText("button");
rl.addView(temp_button, lp_btn);
TextView tv = new TextView(getApplicationContext());
tv.setText("bharat");
tv.setBackgroundColor(Color.GREEN);
RelativeLayout.LayoutParams lp_tv = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp_tv.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rl.addView(tv, lp_tv);
lp.addView(rl);
// for loop will end here
I think you should use listview for your purpose it will be better. Anyway this will also work you have to manage relativelayout array and button array for your purpose.