android java layout + source code confusion - java

I'm a new to android programming. I'm having issues with the layout in my activity. My menu appears like this:
and I've done all the layout work directly through the source code:
enterNameTxt.setText("Enter User Name");
enterNameTxt.setY(200);
enterNameTxt.setX(-600);
userNameTxt.setY(300);
userNameTxt.setX(100);
userNameTxt.setWidth(200);
enterSpeedTxt.setText("Enter Speed");
enterSpeedTxt.setX(-500);
enterSpeedTxt.setY(100);
userSpeedTxt.setX(-400);
userSpeedTxt.setY(700);
userSpeedTxt.setWidth(200);
configButton.setWidth(400);
configButton.setText("Back to Game");
configButton.setY(1000);
and as you can see the speed option doesn't even show up on the screen. And I keep playing with setX, setY, setWidth options but it keeps getting messy.
Is it wrong to do the layout directly through the source code?
I have a two activities but only a layout xml file for one of them. Am I supposed to create another xml file in res/layout section for the menu activity?
I just don't understand when I use the source code and when I should use the layout...
Thanks in advance

Is it wrong to do the layout directly through the source code?
No it's not. But you are strongly advised to use xml layout because it gives you a visual presentation of what you are trying before runtime.
I have a two activities but only a layout xml file for one of them. Am I supposed to create another xml file in res/layout section for the menu activity?
Yes. You have to create an xml file for every activity in your app.
I just don't understand when I use the source code and when I should use the layout...
You should use xml as much as you can. You should only use Java code to set layout attributes when it has to change at runtime. E.g populating a ListView with text from an database or a web service.

Use this code in you java file
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layout_params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams box_params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 40);
LinearLayout.LayoutParams btn_params = new LinearLayout.LayoutParams(120, 40);
ll.setOrientation(LinearLayout.VERTICAL);
EditText et1 = new EditText(MainActivity.this);
et1.setHint("Enter User name");
EditText et2 = new EditText(MainActivity.this);
et2.setHint("Enter speed");
Button btn= new Button(MainActivity.this);
btn.setText("Back to Game");
btn.setGravity(Gravity.CENTER_HORIZONTAL);
ll.addView(et1, box_params);
ll.addView(et2, box_params);
ll.addView(btn, btn_params);
ll.setGravity(Gravity.CENTER);
rl.addView(ll,layout_params );
}
}
You will get required output but it is prefer to use xml file until you don't need dynamic changes in your UI. It is easy to maintain code and design screens using xml files and if there is no need of large dynamic changes you should use xml files. Through Xml files you can check you code on different resolution through graphical representation of code. You can create a xml file in layout folder and can link it to your activity. It is easy, time saving and provide you more accurate designs... :) Please check screen shot for dynamic creation of your required design.
Happy Coding !!!

Related

Android - how to use getId() to access orientation specific layout sub views

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get orientation
LinearLayout layout = isLandscape()
? (LinearLayout) this.findViewById(R.id.main_layout_l)
: (LinearLayout) this.findViewById(R.id.main_layout_p);
Log.i("info", "layout is " + layout.getId());
start();
run();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.e("On Config Change",
(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
? "LANDSCAPE" : "PORTRAIT");
// added -- this fixes the background not showing
setContentView(R.layout.activity_main);
}
I have two layouts (two files, layout/activity_main.xml, layout-land/activity.xml) for both orientations.
What is to be displayed is slightly different depending on the orientation
ie: portrait won't have some extra panels and some stuff has to be moved around.
I need to access the view programmatically.
When accessing 'layout' I get a NullPointerException
each layout orientation has different ids ending in "_p" or "_l" in the xml file to differentiate whether portrait or landscape, when accessing them in java.
Both xml files are currently LinearLayout->TextView
Either way I cant get them to draw
I am using a thread and a clock to handle the drawing calls. Like in a game.
This is needed for doing some various custom animations.
I don't even think the background is drawing.
If I change from LinearLayout and call the TextView directly by its id
it runs without error, but nothing draws.
Try to remove android:configChanges attribute.
It'd be better not to use android:configChanges attribute.
Please refer to Android Developers Site in details
Caution: Handling the configuration change yourself can make it much more difficult to
use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.
https://developer.android.com/guide/topics/resources/runtime-changes

Saving state of UI in Android

I'm making a to-do list app and after user presses the button I create a new GridLayout(and all the data about time and name of the task inside of it) and add it into my RelativeLayout. How do I save those GridLayouts in UI so after the activity is destroyed and launched again those layouts are there.
After pressing the button I trigger the Create Activity method
public void CreateActivity(String name,int hours, int minutes,int i)
{
RelativeLayout.LayoutParams relparams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
relparams.addRule(RelativeLayout.BELOW,i);
relparams.setMargins(0,50,0,100);
Glayouts.add(new GridLayout(this));
Glayouts.get(i+1).setBackgroundColor(Color.GRAY);
Glayouts.get(i+1).setMinimumWidth(relative.getWidth());
Glayouts.get(i+1).setId(i+1);
Glayouts.get(i+1).setPadding(10,0,0,0);
GridLayout.LayoutParams namee = new GridLayout.LayoutParams();
namee.columnSpec = GridLayout.spec(0);
namee.rowSpec = GridLayout.spec(0);
namee.setGravity(Gravity.LEFT);
final TextView Actname = new TextView(this);
Actname.setText(name);
GridLayout.LayoutParams checkbox = new GridLayout.LayoutParams();
checkbox.columnSpec = GridLayout.spec(1);
checkbox.rowSpec = GridLayout.spec(0);
checkbox.setGravity(Gravity.RIGHT);
CheckBox check = new CheckBox(this);
// ADDING TO LAYOUT
Glayouts.get(i+1).addView(Actname,namee);
Glayouts.get(i+1).addView(check,checkbox);
relative.addView(Glayouts.get(i+1),relparams);
Theoretically when you extends View, then you can also override onSaveInstanceState and onRestoreInstanceState methods, where you must provide your own SavedState class that typically extends BaseSavedState. You can find info on that here
In your case, your layout is dynamic, therefore this doesn't really work. To tell you the truth, your layout probably shouldn't be constructed this way, you should be rendering the grid using a RecyclerView based on a "model" that describes this layout, render the items of the grid via the RecyclerView.Adapter, and you should persist either the "model", or the data you use to construct this model along with the user-inputted state so that you can re-construct the model that will be rendered via your RecyclerView.
You can read more about RecyclerView here.
You can read more about data persistence here.
You can read about using onSaveInstanceState to save data in Activities/Fragments across config change and process death (but not finishing then restarting the app) here.
You can’t. The best way to save state is to use some persistence mechanism, for example database (I’d recommend Room as it is officially supported by Google).
After clicking a button, you should put all the needed information (name, hours, minutes) in the database and when Activity is created, you can read all persisted data and - basing on it - create all needed layouts again.
Another option is storing data in SharedPreferences - it is much easier to setup, so you can also start with this solution. Please note, I'm suggesting it as a first step in the world of persistency in Android, not as a preferred solution for storing data.

Adding a xml to a LinearLayout item in android studio

I have xml layout which includes a avatar picture a name and a textbox. These are all in one xml file. I would like to add instances these programmically to a linear layout that is nested in a scoll view. Here is my code.
View v = getLayoutInflater().inflate(R.layout.include_message, null);
LinearLayout stallWall = (LinearLayout) v.findViewById(R.id.stallMessages);
R.layout.include_message = My xml
R.id.stallMessages = Linear Layout
I get no errors and i see no items being added.
I would like to read a array and put a include_message in for each message.
First, I would not recommend using x = y = z = a and so on.
It may be working but it's not easy to read and understand.
as codeMagic said, you should use addView() method to achieve this.
here's an example http://androidexample.com/Dynamically_Create_View_Elements__-_Android_Example/index.php?view=article_discription&aid=115&aaid=137
If you are trying to use a layout defined in an xml file, you can user LayoutInflater like this:
View view = getLayoutInflater().inflate(R.layout.yourfile, null);
layout.addView(view);

Programmatically generated text field is not showing up in Android app

I'm trying to programmatically generate some UI elements onto an android app with Java. I have a ScrollView created in the XML file, and I'm trying to create and add a bunch of UI elements to that ScrollView. All of the UI elements make up 1 bounding box that looks like this:
The bounding box is just a linear layout with an image background, and some text boxes and labels sitting on top of it. I want my code to be modular, so I'm making a class called BoundingBox which should create and add a bounding box to the app every time I instantiate the BoundingBox class.
Here's what I have so far for the BoundingBox class (it's not complete, all it adds so far is a textview with text on it).
public class BoundingBox {
//Instantiate the main app activity.
MainActivity theMainActivity = new MainActivity();
//Create Scrollview object and set it to the XML GUI scrollview
ScrollView sv = (ScrollView) theMainActivity.findViewById(R.id.theMainScrollView);
public BoundingBox(){
//Create linear layout that will sit in the scrollview.
LinearLayout mainLinearLayout = new LinearLayout(theMainActivity);
TextView exerciseName = new TextView(theMainActivity);
TextView repBox1 = new TextView(theMainActivity);
TextView repBox2 = new TextView(theMainActivity);
TextView repBox3 = new TextView(theMainActivity);
TextView repBox4 = new TextView(theMainActivity);
//Add the Linear Layout to the existing scroll view.
sv.addView(mainLinearLayout);
//Add text box to linear layout
mainLinearLayout.addView(exerciseName);
exerciseName.setText("This doesn't work.");
}
}
Here's how I instantiate it in my main Activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
BoundingBox sc = new BoundingBox();
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
The code compiles successfully but no text shows up in my Android app. If I instantiated the class then it should have already ran the code in the BoundingBox constructor, which should have created a text view. I'm not sure what I'm doing wrong, and since the code compiles successfully logcat doesn't tell me anything. If I instantiate the bounding box class in the onCreate() function, the app crashes when starting it. If I instantiate it in the onCreateOptionsMenu function, it runs but it doesn't create a text view.
Your code is so messed up it isn't even close to working.
1)You should never create an activity via new. Ever. It isn't valid.
2)You create a LinearLayout programmatically. But you add it nowhere. If it isn't added to anywhere, where would you expect it to show?
3)Why would you ever want to create a view in options menu code? And once again, you're creating the box but not doing anything with the views it creates. Also, if you want to create a class that holds a bunch of views, it really ought to derive from ViewGroup.
4)Even if 1 was valid (it isn't), doign a findViewById there would return null, because onCreate wasn't called so no contentView was set. But that isn't valid anyway, so don't try to just call it. Instead you want to either pass in the parent view via constructor, or better yet make BoundingBox a ViewGroup subclass and add it to the parent directly.

Android - build dynamic form from code

I have to build a dynamic form in my activity depending on the data retrieved via HTTP that is popullated from XML.
This could be one or more RadioGroups each with exactly three RadioButtons. After RadioGroups I need to place two EditText and one CheckBox control with submit button afterwards.
I have prepared a LinearLayout with vertical orientation and unique ID to be addressed from code and I expect that I can create a form control within a Java code without defining in android XML layout and adding to this LinearLayout.
I was googling for a few hours but could not find any example how to do this.
Could anyone please provide some example how to create e.g. one RadioGruop with 1-2 RadioButtons and add it to the LinearLayout (that is prepared in XML layout)?
Many thanks for any advice!!!
These widgets can be create like every other widgets:
final Context context; /* get Context from somewhere */
final LinearLayout layout = (LinearLayout)findViewById(R.id.your_layout);
final RadioGroup group = new RadioGroup(context);
final RadioButton button1 = new RadioButton(context);
button1.setId(button1_id); // this id can be generated as you like.
group.addView(button1,
new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT));
final RadioButton button2 = new RadioButton(context);
button1.setId(button2_id); // this id can be generated as you like.
button2.setChecked(true);
group.addView(button2,
new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT));
layout.addView(group,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
I haven't tested this code, so it may contain some errors. But I hope you'll get the idea.

Categories

Resources