I am creating my own UI component class by extending layout class. Now instead of adding my custom attributes like height , width etc in string xml resources as separate xml, I want to define in Activity class itself. I don't want to add in xml and then refer it from R class in my code. Is there any way to define and access attributes in code itself?
Here is a code sample from Pro Android 4:
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
{
private LinearLayout nameContainer;
private LinearLayout addressContainer;
private LinearLayout parentContainer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
createNameContainer();
createAddressContainer();
createParentContainer();
setContentView(parentContainer);
}
private void createNameContainer()
{
nameContainer = new LinearLayout(this);
nameContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
nameContainer.setOrientation(LinearLayout.HORIZONTAL);
TextView nameLbl = new TextView(this);
nameLbl.setText("Name: ");
TextView nameValue = new TextView(this);
nameValue.setText("John Doe");
nameContainer.addView(nameLbl);
nameContainer.addView(nameValue);
}
private void createAddressContainer()
{
addressContainer = new LinearLayout(this);
addressContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
addressContainer.setOrientation(LinearLayout.VERTICAL);
TextView addrLbl = new TextView(this);
addrLbl.setText("Address:");
TextView addrValue = new TextView(this);
addrValue.setText("911 Hollywood Blvd");
addressContainer.addView(addrLbl);
addressContainer.addView(addrValue);
}
private void createParentContainer()
{
parentContainer = new LinearLayout(this);
parentContainer.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
parentContainer.setOrientation(LinearLayout.VERTICAL);
parentContainer.addView(nameContainer);
parentContainer.addView(addressContainer);
}
}
Also See these for more functionalities:
Layout Params Linear Layout
ViewGroup Layout Params
StackOverflow Setting Layout params
Related
I am extremely new to Android Studio, and as a learning exercise, I am trying to create an application without using any xml files other than manifest.
I want to make an activity, layout, toolbar, and drawer menu completely within Java. I know it is not how things are normally done, and I am likely causing myself a lot of unnecessary stress, but, as I said, this is a learning exercise.
Everything seems to execute, but the toolbar does not display. Also, getSupportActionBar().getHeight() returns zero.
Any help is appreciated!
Thanks,
John
Here is my Activity.java
package com.example.john.myblankapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.Snackbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by John on 7/3/2016.
*/
public class MyActivity extends AppCompatActivity {
private RelativeLayout myRelativeLayout;
private LinearLayout myLinearLayout;
private Toolbar myToolbar;
private TextView myTextView;
private ActionBar myActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the main layout programmatically
createRelativeLayout();
createLinearLayout();
// I have tried it with LinearLayout and RelativeLayout
setContentView(myLinearLayout);
// Create the toolbar layout programmatically
createToolbarLayout();
//myLinearLayout.addView(myToolbar); // that turned the whole screen red
setSupportActionBar(myToolbar);
myActionBar = getSupportActionBar();
myActionBar.setDisplayHomeAsUpEnabled(true); // new test - didn't help
// Create the text programmatically
myLinearLayout.addView(createTextView());
Snackbar.make(myTextView, "ActionBarHeight="+myActionBar.getHeight(),
Snackbar.LENGTH_LONG)
.setAction("Action", null).show(); // displays 0
}
private void createRelativeLayout() {
myRelativeLayout = new RelativeLayout(this);
// Specifies the layout properties
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
myRelativeLayout.setLayoutParams(relativeParams);
}
private void createLinearLayout() {
myLinearLayout = new LinearLayout(this);
// Specifies the layout properties
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
myLinearLayout.setLayoutParams(linearParams);
}
private Toolbar createToolbarLayout() {
myToolbar = new Toolbar(this);
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
R.attr.actionBarSize, Gravity.TOP
);
myToolbar.setTitle("My Toolbar");
myToolbar.setLayoutParams(toolBarParams);
myToolbar.setBackgroundColor(Color.RED);
myToolbar.setVisibility(View.VISIBLE);
return myToolbar;
}
private TextView createTextView() {
myTextView = new TextView(this);
// Set initial layout parameters
RelativeLayout.LayoutParams textViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
// Set alignment parameters
//textViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
myTextView.setText("Here is some text");
myTextView.setLayoutParams(textViewParams);
return myTextView;
}
}
You also need to add toolbar to linear layout.
// Create the toolbar layout programmatically
myLinearLayout.addView(// Create the toolbar layout programmatically
createToolbarLayout(););
I would recommend making the toolbar a custom view and just set the dimensions in the layout screen. You can declare the custom view as a toolbar if you import the toolbar package. Then you can use all the toolbar commands built in to add a title and items.
Hope this helps!
I'm pretty new to android programming. And now, I'm trying to create a ImageView programmatically. But not in the MainActivity, but in a second class I created.
Here's my code:
package com.example.joystick;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class Joystick extends Activity{
ImageView imView;
RelativeLayout Layout;
public void create(int x, int y, RelativeLayout layout) {
Layout = layout;
imView = new ImageView(this);
imView.setImageResource(R.drawable.joystickknuppel);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);
Layout.addView(imView);
}
}
If I load the app to my device, it crashes. But if I copy the "create" method into MainActivity, it works well.
Can someone tell me why this happens, and how to fix it?
Thanks a lot!
Replace this method with this code...onCreateView(...)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
Layout = layout;
imView = new ImageView(this);
imView.setImageResource(R.drawable.joystickknuppel);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);
Layout.addView(imView);
return view;
}
Don't forget to initialize the Layout Layout
Is Joystick an Activity?? If not, you don't need to extend Activity instead pass a reference of your current activity and then use it inside your create method.
Here's how.
public class Joystick {
ImageView imView;
RelativeLayout Layout;
Activity activity;
public JoyStick(Activity activity)
{
this.activity=activity;
}
public void create(int x, int y, RelativeLayout layout) {
Layout = layout;
//here's the change
imView = new ImageView(activity);
imView.setImageResource(R.drawable.joystickknuppel);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutPa rams.WRAP_CONTENT);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);
Layout.addView(imView);
}
}
From your MainActivity you can acces it via.
JoyStick joyStick=new JoyStick(this);
//add your params
joystick.create(x,y,relativeLayout);
Call this create method from onCreate and send layout as a parameter to this function. Actually you are trying to access the view that is not registered yet. So in this case you will get null pointer exception.
You must have activity referance to add control on that perticular activity
package com.example.joystick;
import android.app.Activity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class Joystick{
ImageView imView;
RelativeLayout Layout;
public void create(Activity act,int x, int y, RelativeLayout layout) {
Layout = layout;
imView = new ImageView(act);
imView.setImageResource(R.drawable.joystickknuppel);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);
Layout.addView(imView);
}
}
if you put 'this' it means it point to your Joystick class which extends Activity but not actually Intent from anywhere.
from which Activity you call create mathod there you have to pass 'this' as Activity parameter.
I am trying to create a horizontalscrollview in the onCreate() method of my first activity, since I want to make a large number of textviews to scroll through. Here is what I have so far:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout linscrollview;
HorizontalScrollView scrollview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollview = (HorizontalScrollView) findViewById(R.id.scrollview_layout);
linscrollview = new LinearLayout(this);
for(int i=0; i<5; i++) {
TextView tv = new TextView(this);
tv.setWidth(LayoutParams.WRAP_CONTENT);
tv.setHeight(LayoutParams.WRAP_CONTENT);
tv.setText("" + i);
tv.setTextSize(20);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
tv.setLayoutParams(params);
tv.setId(i);
linscrollview.addView(tv);
}
scrollview.addView(linscrollview);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I am not getting any errors, however no textviews are showing up.
Your problem is likely to do with the setWidth and setHeight methods. They set the exact value of the TextView width and height in pixels as described in the documentation:
Makes the TextView exactly this many pixels wide. You could do the
same thing by specifying this number in the LayoutParams.
http://developer.android.com/reference/android/widget/TextView.html#setWidth(int)
What you want to do is set the LayoutParams for the TextView as you are already going slightly further down your code. So just get rid of those two method calls and it should work.
this s a chunk of code to implement horizontal scrolling for textview, modify the same according to requirements.
textView.setHorizontallyScrolling(true);
textView.setSingleLine(true);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setHorizontalScrollBarEnabled(true);
textView.setSelected(true);
Please do like this
linscrollview .setOrientation(LinearLayout.HORIZONTAL);
and ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
My coding here. it will gives you list like horizonatal listview
String[] name={"PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT","PRASHANT"} ;
myLInearLayoutmain =(LinearLayout) findViewById(R.id.linearLayoutmain);
for(int i =0;i<6;i++)
{
LinearLayout li=new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
li.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams paramsnew = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params1.setMargins(30, 20, 30, 0);
//add textView
valueTV = new TextView(this);
valueTV.setText(""+name[i]);
valueTV.setId(5);
valueTV.setLayoutParams(paramsnew);
valueTV.setGravity(Gravity.CENTER);
// adding Button to linear
valueB = new Button(this);
valueB.setText(""+name[i]);
valueB.setId(i);
valueB.setLayoutParams(params);
valueB.setOnClickListener(this);
valueB.setGravity(Gravity.CENTER);
//add the textView and the Button to LinearLayout
li.addView(valueTV);
li.addView(valueB);
li.addView(img);
li.setLayoutParams(params1);
myLInearLayoutmain.addView(li);
}
i've created an android application which creates 50 button dynamically,which works perfectly, but the problem is i'm getting bad view when i put some background color for these buttons dynamically using code given below
buttons[i][j].setTextColor(Color.BLACK);
buttons[i][j].setBackgroundColor(Color.GREEN);
my code is as given below, can anyone please tell me some solution for this
my Android Platform is 2.3.3
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class MyMain extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mymain);
createCalender();
}
public void createCalender()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
LinearLayout rowLayout=null;
Button[][] buttons = new Button[10][5];
int count=51;
int tab=1;
for (int i = 0; i<10; i++)
{
if(count%5==1)
{
rowLayout = new LinearLayout(this);
rowLayout.setWeightSum(5);
layoutVertical.addView(rowLayout,param);
count=count-5;
}
for(int j=0;j<5;j++)
{
buttons[i][j]=new Button(this);
buttons[i][j].setText(""+tab);
buttons[i][j].setHeight(35);
buttons[i][j].setWidth(75);
buttons[i][j].setTextColor(Color.BLACK);
buttons[i][j].setBackgroundColor(Color.GREEN);
tab++;
rowLayout.addView(buttons[i][j],param);
}
}
}
}
You should add some margin to leave these buttons some breathing room.
// First try with WRAP_CONTENT
LinearLayout.LayoutParams paramForButtons = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
// If the buttons look too small using WRAP_CONTENT, change to MATCH_PARENT
// Set the margins in this case
LinearLayout.LayoutParams paramForButtons = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
paramForButtons.setMargins(10, 10, 10, 10);
Replace the last line of your for loop with:
rowLayout.addView(buttons[i][j],paramForButtons);
I need to overlap an image view with textview. And this combined view will be repeated 100 times in a LinearLayout. I was thinking of using FrameLayout in LinearLayout and Repeating the FrameLayout in LinearLayout 100 times when FrameLayout holds the imageview and textview overlapped.
Need to do this programatically not from xml file.
I added the image and textview to framelayout first then tried to add the framelayout to linearlayout. But it says : the specified child has already a parent.. so not working. Can you please show me in code? Thanks for your help.
it is going to be like this, but need to be done programmaticaly
---linear layout--------------
------------------------------
|frame layout----------------|
||txt view on top of img view|
------------------------------
frame layout will be repeated|
---/end of linear layout------
Also here is the separated code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout dynamicview = (LinearLayout) findViewById(R.id.main_layout);
FrameLayout barFrameLayout = new FrameLayout(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
Gravity.CENTER);
barFrameLayout.setLayoutParams(params);
LinearLayout.LayoutParams slparams1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i = 65; i <= 75; i++) {
TextView catTV = new TextView(this);
catTV.setLayoutParams(slparams1);
catTV.setText("===" + Character.toString((char) i) + "===");
catTV.setTextSize(32);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.ic_launcher);
iv.setLayoutParams(slparams1);
barFrameLayout.addView(catTV);
barFrameLayout.addView(iv);
dynamicview.addView(barFrameLayout);
}
}
Here is the code to demonstrate what you are trying to achieve. I have used RelativeLayout, which is very flexible, you can position the elements easily relative to others.( if you need to change to FrameLayout you can change ).
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ExampleLayout extends LinearLayout{
public ExampleLayout(Context context,AttributeSet attrs){
super(context,attrs);
for(int i =0; i< 100; i++){
RelativeLayout childLayout = new RelativeLayout(context);
ImageView img = new ImageView(context);
TextView text = new TextView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
childLayout.addView(img, params);
params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
childLayout.addView(text, params);
LinearLayout.LayoutParams parentParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
this.addView(childLayout,parentParams);
}
}
}
You can then use the ExampleLayout class to add it to any of the layout.xml file.
FrameLayout is designed to block out an area on the screen to display
a single item
(source: http://developer.android.com/reference/android/widget/FrameLayout.html).
Anyway, you have to create new FrameLayouts not use the same.
When you're doing:
barFrameLayout.addView(catTV);
barFrameLayout.addView(iv);
dynamicview.addView(barFrameLayout);
you're always adding these new objects (catTV and iv) to the same instance of a FrameLayout (barFrameLayout).
I don't think that's what you wanted to do.