Code :
LinearLayout linearLayout2;
final JSONArray answer=jsonObject1.getJSONArray("answer");
//Here get Answer from question
((ViewGroup) findViewById(R.id.linearLayout2)).removeView(linearLayout2); //Here remove preselected radiobuttons
linearLayout2 = new LinearLayout(TestActivity2.this); //Here create new viewgroup when user click next and previous
linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
linearLayout2.setGravity(Gravity.FILL_HORIZONTAL);
indexAns=new String[answer.length()];
for(int j=0;j<answer.length();j++)
{
final JSONObject jsonObject2 = answer.getJSONObject(j);
final String answer_ans=jsonObject2.getString("answer_ans"); //get answer from loop
answer_id=jsonObject2.getString("answer_id");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//Here create radio buttons depending on answer loop
final TextView textBtn = new TextView(TestActivity2.this);
textBtn.setId(Integer.parseInt(answer_id));
textBtn.setLayoutParams(params);
textBtn.setAllCaps(true);
textBtn.setTextSize(12);
textBtn.setPadding(5,5,5,5);
textBtn.setGravity(Gravity.LEFT | Gravity.CENTER |Gravity.RIGHT);
textBtn.setTextColor(Color.parseColor("#000000"));
indexAns[j]=answer_id;
You may want to post your layout xml files. Looks like you are manipulating the layout programatically, which, in most cases in unnecessary. You can accomplish the same goal via xml layout files.
Also, you can save a lot of time using styles for formatting.
Check out the following layout documentation
https://developer.android.com/guide/topics/ui/declaring-layout.html
Check out the TextView documentation:
https://developer.android.com/reference/android/widget/TextView.html
Related
I'm adding multiple Views by code into Layout. I need each new View to be above previous one(top of the parent layout).
EDIT: To be more accurate I'll describe what the app module should does. User start with clean screen and one button at the bottom of the screen. The button adds a View at the top of the screen. Next clicks should add next views above previous ones to make the newest View be on the top of a container. The app saves state and on restart user see views in the same order.
Call the following method from Button's onClick Event.
private final int LAYOUT_TOP_INDEX = 0;
private void addViewOnTop(View view){
if(layout != null && view !=null)
layout.addView(view, LAYOUT_TOP_INDEX);
}
where 'layout' is your Layout (e.g., LinearLayout) to which the View is to be added.
Would really need more information from you to give a more accurate answer, but if you're saying what i think you are then you can just add these views to a LinearLayout with orientation set to vertical.
And assuming you're iterating through a list to dynamically add views, instead of incrementing from 0, increment down from the size of the list.
for(int i = size; i >= 0; i--){
linearLayout.add(new TextView(Context));
}
View positions inside ViewGroups are defined by the LayoutParams
How does this happen? Views pass their LayoutParams to their parent ViewGroups
//100% programatic approach with simple LayoutParams
LinearLayout myLinearLayout = new LinearLayout(this);
//if the **parent** of the new linear layout is a FrameLayout
FrameLayout.LayoutParams layoutParams =
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
//or if you have the XML file you don't have to worry about this
//myLinearLayout = (LinearLayout)findViewById(R.id.my_simple_linear_layout);
//you could have a LinkedList<TextView>
LinkedList<TextView> textViewList = new LinkedList<>();
//assuming the order is the correct order to be displayed
Iterator<TextView> descendingIterator = textViewList.descendingIterator();
while(descendingIterator.hasNext())
{
//just add each TextView programatically to the ViewGroup
TextView tView = descendingIterator.next();
myLinearLayout.addView(tView);
}
Just like we defined LayoutParams for the LinearLayout we could also define LayoutParams for the TextView
IMPORTANT: when setting LayoutParams you need to be sure they fit the VIEWGROUP, that is the parent of the View being added
private TextView textViewFactory(String myText) {
TextView tView = new TextView(getBaseContext());
//controling the position relatively to the PARENT
//because you are adding the textview to a LINEAR LAYOUT
LinearLayout.LayoutParams paramsExample =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
tView.setLayoutParams(paramsExample);
//configuring the insides of the textview
//you can also do all kinds of stuff programatically
tView.setGravity(Gravity.CENTER_HORIZONTAL);
tView.setPadding(10, 10, 10, 10);
tView.setTypeface(Typeface.DEFAULT_BOLD);// (null, Typeface.BOLD_ITALIC);
tView.setTypeface(Typeface.SANS_SERIF);
tView.setTypeface(null, Typeface.ITALIC);
tView.setTypeface(Typeface.defaultFromStyle(R.style.AppTheme));
tView.setId(R.id.aux_info);
tView.setText(myText);
//.........all kinds of stuff really
return tView;
}
If you mean adding a view programmatically so that the new one is added above the previous one, instead of below it, then I suggest this:
Maintain an ArrayList with the items you want to turn into views
Put them into a ListView
When you want to add a new view that must appear at the top of the list, insert it as the first element of your ArrayList and recreate the ListView from it.
I am trying to programmatically add LinearLayouts inside an existing RelativeLayout. Each LinearLayout will contain some buttons and I want to be able to toggle the visibility of each set of buttons by setting the visibility of the container LinearLayout.
// We iterate over a list and call the following to create the new
// layout assigning an index from a int counter
LinearLayout LL = new LinearLayout(MainActivity.this);
LL.setOrientation(LinearLayout.VERTICAL);
LL.setId(nextId);
LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LL.setWeightSum(6f);
LL.setLayoutParams(LLParams);
LinearLayout mll=((LinearLayout) findViewById(R.id.menuLayout));
mll.addView(LL);
My problem comes when I try to retrieve these layouts later, for instance to be able to toggle their visibility on/off. I thought I would be able to use
LinearLayout ll = (LinearLayout) findViewById(layoutIndex);
But findViewById() gives me an error when I try to supply an int, it wants a resource ID. Is there an easy way I can convert the ints that I have assigned as the Ids for these layouts to R.id.XXX ids?
Thanks,
Andy
findViewById(id) looks up elements that were included as part of the XML defining a layout.
You will probably have better luck with getChildAt(index), which returns the View at the passed index.
Yes! Find all LinearLayout in a container without using ID.
LinearLayout mll= (LinearLayout) findViewById(R.id.menuLayout);//container
for(int i=0; i<mll.getChildCount(); ++i) {
View nextChild = mll.getChildAt(i);
if (nextChild instanceof LinearLayout ) {
//TODO add your code here nextChild is a LL that you wanna find
}
}
I want to add multiple buttons to a layout programmatically.
However, count of buttons is different every time and I just want them to placed next to each other with a wrap content width. After a line is filled, it should go to next line and continue that way.
What is the cleanest way to achieve that?
Thanks.
LinearLayout verticalLayout = new LinearLayout(context);
verticalLayout.setOrientation(LinearLayout.VERTICAL);
while(isActive) {
LinearLayout horziontalLayout = new LinearLayout(context);
horziontalLayout.setOrientation(LinearLayout.HORIZONTAL);
add buttons here..
//Example Button button = new Button(context);
//horziontalLayout.addView(button);
verticalLayout.addView(horziontalLayout);
isActive = false // when youe done filling up buttons..
}
easiest way should be having a vertical LinearLayout in wich you add multiple horizontal LinearLayout
//vertical one
LinearLayout vlinear = new LinearLayout(this);
vlinear.setOrientation(LinearLayout.VERTICAL);
LayoutParams vlinearParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
vlinear.setLayoutParams(vlinearParams);
parentgroup.addView(vlinear);
//horizontal lines
for (int i=0;i<numlines){
LinearLayout hlinear = new LinearLayout(this);
hlinear.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams vlinearParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
hlinear.setLayoutParams(hlinearParams);
vlinear.addView(hlinear);
///add the loop for adding cells
for...
hlinear.addView(cell);
}
I need to start an application that contains a list of text with images. I need to display these text messages in a list with images. I am displaying these messages with images by using linear layouts as shown below.
for(int i=0;i<messages.size();i++)
{
FrameLayout f1= new FrameLayout(this);
LinearLayout l1 = new LinearLayout(this);
LinearLayout l2 = new LinearLayout(this);
im =new ImageView(this);
TextView tv =new TextView(this);
tv.setText(messages.get(i).getmessage());
im.setImageResource(R.drawable.person);
l1.addView(tv);
l2.addView(im);
f1.addView(l1);
f1.addView(l2);
((LinearLayout)findViewById(R.id.LinearlayoutMessage)).addView(f1);
}
After some time I need to refresh only images in the image view. I am trying to do this by setting id's to each image view's but I get only last image view id.
I know there is listview, but is it suitable for my requirement? I don't know how can I do my task. Can anyone please help me?
My suggestion would be to use Adapter for showing image and respective text. It will help you get selected/focused item.
Please share result.
I did something similar.. I just did a list of TextViews (two TextView per row), and i needed to update one TextView in the list.. What i did was a vertical LinearLayout, and add Horizontal LinearLayouts that contained my TextViews.. Then i had a List of strings to look for the index of the one i needed to modify, and then search it with LinearLayout.getChildAt(int) and update the value...
CODE:
I have a list of strings and a counter that says how many times come this string...
private ArrayList<String> strList;
private ArrayList<Integer> counterList;
When the String is new:
strList.add(new_string);
TextView str = new TextView(getApplicationContext());
str.setText(sTemp);
str.setLayoutParams(strsTextView.getLayoutParams());
TextView strcounter = new TextView(getApplicationContext());
strcounter.setLayoutParams(counterTextView.getLayoutParams());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,1);
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(str, layoutParams);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,3);
counterList.add(1);
strcounter.setText("1");
ll.addView(strcounter, layoutParams);
mLinearLayout.addView(ll,new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
I check if the String is not new (is already in the strList)if(strList.indexOf(sTemp)!=0) and then do as follows:
Integer intaux =counterList.get(index);
intaux++;
counterList.set(index, intaux);
LinearLayout aux = (LinearLayout)mLinearLayout.getChildAt(index);
TextView aux2 = (TextView)aux.getChildAt(1);
aux2.setText(Integer.toString(intaux));
I hope i didn't miss anything and that this works for you.. If you don't understand anything tell me an i try to explain/correct it.
PS: I suppose that the Adapter solution of #abhijeet is a more elegant version of my implementation, but i haven't done it.
I want to create a relative Layout dynamically through code with 2 Textviews one below the other.How to implement android:layout_below property through code in Android.
can anyone help me in sorting out this issue.
Thanks in Advance,
final TextView upperTxt = (...)
upperTxt.setId(12345);
final TextView lowerTxt = (...);
final RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(this, null);
params.addRule(RelativeLayout.BELOW, 12345);
lowerTxt.setLayoutParams(params);
Here is my solution for my special Problem.
In case the username wouldn't be found in the db i had to create a RelativeLayout that looks like the xml-generated one.
// text view appears on top of the edit text
enterNameRequest = new TextView(mainActivity.getApplicationContext());
// fill the view with a string from strings.xml
enterNameRequest.setText(mainActivity.getResources().getString(R.string.enterNameRequest));
// edit text appears below text view and above button
enterName = new EditText(mainActivity.getApplicationContext());
enterName.setId(667);
// button appears at the bottom of the relative layout
saveUserName = new Button(mainActivity.getApplicationContext());
saveUserName.setText(mainActivity.getResources().getString(R.string.useUserName));
saveUserName.setId(666);
// generate the relative layout
RelativeLayout layout = new RelativeLayout(mainActivity.getApplicationContext());
layout.setId(668);
// set a background graphic by its id
layout.setBackgroundDrawable(mainActivity.getApplicationContext().getResources().getDrawable(R.drawable.background_head_neutral));
// runtime told me that i MUST use width and height parameters!
LayoutParams params2 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ABOVE, 666);
enterName.setLayoutParams(params2);
LayoutParams params3 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params3.addRule(RelativeLayout.ABOVE, 667);
enterNameRequest.setLayoutParams(params3);
LayoutParams params4 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params4.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 668);
saveUserName.setLayoutParams(params4);
// add views
layout.addView(enterNameRequest);
layout.addView(enterName);
layout.addView(saveUserName);
/* todo: set button action */
mainActivity.setContentView(layout);
What i found out additionally:
It is not so good to manipulate the layout manually from within java!
You should better use a new Activity and set a new layout in it.
This way, the application-code is readable a lot better!
I even tried to set several layouts (not manually, but wit setContentView) in one activity, and it turned out that i didn't know where what was accessing what else... Also, i had a great problem in adding onClickListeners... so you better use -- android:onClick="myButtonMethod" -- in your button tag in the xml and have a method in your according activity, which uses the layout, like this:
public void myButtonMethod(View v){
// do stuff
}
This improves performance because you are not using additional Listeners - but you use the already available Listener that is bound to your activity in every case.
u can try this
LinearLayout.LayoutParams leftMarginParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);``
leftMarginParams.leftMargin = 50;
Button btn1 = new Button(this);
btn1.setText("Button1");
linLayout.addView(btn1, leftMarginParams)