I want to add more LinearLayout in a empty one when I press "add button".
When I press the first time "it works", the empty LinearLayout show that I want but if I press the button again don't work ( LogCat show me that occurs a NullPointerException). I see that its not create a new one LinearLayout below the previous one and no idea how solve it.
Let me show you part of my code:
First, I created
static int ID=0;
...
LinearLayout mLayout []= new LinearLayout[10];
...
OnCreate:
...
mLayout[ID] = (LinearLayout) findViewById(R.id.linearLayout_expandir);
...
Then:
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout[ID].addView(createNewTextView("Contain: ", ID));
mLayout[ID].addView(createNewEditText(ID));
mLayout[ID].addView(createNewTextView("Nº Liter: ",ID));
mLayout[ID].addView(createNewEditText(ID));
ID++;
}
};
}
XML: (This LinearLayout is empty: no EditText, Buttons etc and is inside another LinearLayout)
(More code from other LinearLayouts)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.66"
android:orientation="horizontal"
android:id="#+id/linearLayout_expandir">
</LinearLayout>
(More code from other LinearLayouts)
Thank you for your time!
One question: you only have 1 LinearLayout, why do you create an array of LinearLayout while you're not adding another LinearLayout to the LinearLayout?
The error probably occurred when the ID become 1, mLayout[1] has not been initialized and you're trying to add another view to it.
LinearLayout expandir = (LinearLayout) findViewById(R.id.linearLayout_expandir);
in the onClick() method:
public void onClick(View v) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.addView(createNewTextView("Contain: ", ID));
linearLayout.addView(createNewEditText(ID));
linearLayout.addView(createNewTextView("Nº Liter: ",ID));
linearLayout.addView(createNewEditText(ID));
expandir.addView(linearLayout);
ID++;
}
I've created a solution for you. This activity has a button that will generate layouts for you. I use an arraylist instead of an array but the idea is the same.
This is a picture of many nested layouts that have been created using this demo.
Once you get this code in your project, you will just have to add the TextView/Edit Text code that you mentioned. Let me know if you have any questions. :)
public class LinearLayoutActivity extends Activity {
/*This linear layout is the first container*/
LinearLayout outerMostLayout;
/*This array holds the linear layouts that you will create dynamically*/
List<LinearLayout> subLayouts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_layout);
// Initialize your views
outerMostLayout = (LinearLayout) findViewById(R.id.container_layout);
subLayouts = new ArrayList<LinearLayout>();
Button button = (Button) findViewById(R.id.button);
// Set the button onclick
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get a reference to the container layout
LinearLayout container = outerMostLayout;
if (!subLayouts.isEmpty()) {
// Check to see if we have created any yet new containers yet
//-- If we have, then use the newest container
container = subLayouts.get(subLayouts.size() - 1);
}
// Initialize the new layout with padding to show the change
LinearLayout linearLayout = new LinearLayout(LinearLayoutActivity.this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(linearLayoutParams);
linearLayout.setPadding(16, 16, 16, 16);
// Add textview with linear layout name
TextView textView1 = new TextView(LinearLayoutActivity.this);
textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
textView1.setText("Linear Layout: " + (subLayouts.size() + 1));
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
linearLayout.addView(textView1);
// Add the layout to the array
subLayouts.add(linearLayout);
// Set the color of the new layout so that we can see the change
int size = subLayouts.size();
if (size % 2 == 0) {
// Every even layout will be blue
linearLayout.setBackgroundColor(getResources().getColor(R.color.blue));
} else {
// every odd layout will be red
linearLayout.setBackgroundColor(getResources().getColor(R.color.red));
}
// Finally, add the linear layout to the container layout
container.addView(linearLayout);
}
});
}
}
Here is the Layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/red"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"/>
<LinearLayout
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
</LinearLayout>
</LinearLayout>
Related
I have a VideoView and a ListView in my RelativeLayout parent view. When the activity is Created by default the VideoView is below the ListView but I desire to change this and place the ListView below the VideoView when a button is clicked at runtime... I have tried this but am getting an error that :"Circular dependencies are not allowed in RelativeLayout"..
Here is the code I have that is throwing an exception
class Audio_Player:AppCompatActivity{
ListView audiolist;
VideoView video;
Button change;
protected override void OnCreate(Bundle savedInstanceState){
audiolist=(ListView)FindViewById<ListView>(Resource.Id.myaudiolist;
video=(VideoView)FindViewById<VideoView>(Resource.Id.myvideo);
change=(Button)FindViewById<Button>(Resource.Id.button1);
change.Click += layout_change;
}
//method to change the layout rule on button click
private void layout_change(object sender,EventArgs e) {
RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.WrapContent);
LayoutParams.AddRule(LayoutRules.Below,video.Id);
audiolist.LayoutParameters=layoutParams;
}
}
Circular dependencies are not allowed in RelativeLayout
From the shared error, you can not modify the inner existed control of the RelativeLayout. That means you only can add View from outside of the Root RelativeLayout.
For example , create another_layout.xml as follows, and it only contains a Control. You could modify it with your needs control.
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/AnotherRootView"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:text="AnotherListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="25px"
android:id="#+id/AnotherListView" />
</LinearLayout>
Now back to Root RelativeLayout, and add android:id="#+id/RootView" in its xml.
Then we can add another_layout.xml in Root RelativeLayout as follows:
private void Change_Click(object sender, System.EventArgs e)
{
// get root view
RelativeLayout rootView = (RelativeLayout)FindViewById<RelativeLayout>(Resource.Id.RootView);
// set layout params
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.WrapContent);
layoutParams.AddRule(LayoutRules.Below, video.Id);
// get another layout
LayoutInflater inflater = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService);
LinearLayout linearLayout = (LinearLayout)inflater.Inflate(Resource.Layout.another_layout, null,true);
// get and set data for anther list view
ListView anotherListView = (ListView)linearLayout.FindViewById(Resource.Id.AnotherListView);
// we can remove the previous list view
rootView.RemoveView(audiolist);
// add another list view which inside the anther layout
rootView.AddView(linearLayout, layoutParams);
}
Please bear with me as I am new to the use of Views and Layouts.
I am trying to create an application in which the user can enter a text field, press a button and have a new text field appear and they can continue adding text fields in this way.
My solution was to have the top level be a scrollview and then have a relative view as a child within that(this way I can then programatically insert more editviews in my code with the OnClick() listener.
I have seen and read a couple of other posts pertaining to relative views but it seems there is still something that I am missing. I have tried
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create_accounts"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nic.mybudget.CreateAccountsActivity">
<RelativeLayout
android:id="#+id/activity_create_accounts_relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/activity_name"
android:inputType="textAutoComplete"
android:layout_alignParentTop="true"
android:id="#+id/activity_createAccounts_relativeLayout_activityName"/>
<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/activity_createAccounts_relativeLayout_activityName"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_addButton" />
<Button
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/activity_create_accounts_relativeLayout_activityName_addButton"
android:layout_centerHorizontal="true"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_saveButton" />
</RelativeLayout>
And here is the Code where I try to add new editviews.
public class CreateAccountsActivity extends Activity {
static private final String TAG = "MAIN-Activity";
int numAccounts = 0;
int lastAccountID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_accounts);
final RelativeLayout Relative = (RelativeLayout) findViewById(R.id.activity_create_accounts_relativeLayout);
final TextView oldAccount = (TextView) findViewById(R.id.activity_createAccounts_relativeLayout_activityName);
final TextView newAccount = new TextView(this);
final Button addNewAccountButton = (Button) findViewById(R.id.activity_create_accounts_relativeLayout_activityName_addButton);
addNewAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "addNewAccountOnClick");
numAccounts = numAccounts+1;
int newAccountID = oldAccount.getId() + numAccounts;
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
newAccount.setLayoutParams(rlp);
newAccount.setHint("Hint" );
newAccount.setId(newAccountID);
Relative.addView(newAccount);
RelativeLayout.LayoutParams blp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
blp.addRule(RelativeLayout.BELOW, newAccountID-1);
addNewAccountButton.setLayoutParams(blp);
}
});
}
}
As you can see what I am trying (and failing) to do is add the new edit view at the top of the page and simply push everything else down the page. What am I getting wrong here with the relative layout?
Any help is appreciated.
First thing View with id activity_createAccounts_relativeLayout_activityName is EditText and you are casting it with TextView so that is wrong cast it to EditText.
And to your actual problem:
You are using same EditText instance with variable newAccount and adding it again in relative layout if you want to add one more EditText in relative layout you have to initialise EditText inside onclicklistener.
Just add one line newAccount= new EditText(context)in your onclicklistener code before line numAccounts = numAccounts+1;
Happy Coding !
I need to detect which is the clicked image in my application. I try a lot of ways of to do that. I generate Imageview objects dinamically from a Integer Array and i detect that one image is clicked but not which.
I need to put two rows of images but i need that the movement of this images be booth at the same time, not individually. I made a horizontalScrollView with two layouts, one vertical a one horizontal. I put two imageviews in the vertical and send this layout to the horizontal layout through a loop for.
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutContenedor"
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"
tools:context=".MainActivity" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="#+id/linearLayoutHorizontal"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
My Activity:
public class MainActivity extends Activity implements OnClickListener{
private LinearLayout layoutDinamicoHorizontal;
private LinearLayout layoutGlobal;
private Integer[] listaPeliculas = { R.drawable.android1, R.drawable.android2,
R.drawable.android3, R.drawable.android4, R.drawable.android5, R.drawable.android6,
R.drawable.android7, R.drawable.android8, R.drawable.android9, R.drawable.android10,
R.drawable.android11, R.drawable.android12, R.drawable.android13, R.drawable.android14,
R.drawable.android15, R.drawable.android16, R.drawable.android17, R.drawable.android18,
R.drawable.android19, R.drawable.android20, R.drawable.android21, R.drawable.android22,
R.drawable.android23, R.drawable.android24, R.drawable.android25, R.drawable.android26,
R.drawable.android27, R.drawable.android28, R.drawable.android29, R.drawable.android30};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// layout in variable of LinearLayout type
layoutDinamicoHorizontal = (LinearLayout) findViewById(R.id.linearLayoutHorizontal);
layoutGlobal = (LinearLayout) findViewById(R.id.layoutContenedor);
layoutGlobal.setBackgroundResource(R.drawable.fondodepantallacarrusel);
// create ImageView
ImageView imageViewDinamicoArriba;
ImageView imageViewDinamicoAbajo;
for (int i = 0; i < 30; i = i+2){
// Creamos a new object from ImageView class
imageViewDinamicoArriba = new ImageView(this);
imageViewDinamicoAbajo = new ImageView(this);
// padding to objects of ImageView class
imageViewDinamicoArriba.setPadding(10, 15, 10, 15);
imageViewDinamicoAbajo.setPadding(10, 15, 10, 15);
Drawable imagenArriba = getResources().getDrawable(listaPeliculas[i]);
Drawable imagenAbajo = getResources().getDrawable(listaPeliculas[i+1]);
// Se los pasamos a los objetos
imageViewDinamicoArriba.setImageDrawable(imagenArriba);
imageViewDinamicoAbajo.setImageDrawable(imagenAbajo);
LinearLayout vertical = new LinearLayout(this);
vertical.setOrientation(LinearLayout.VERTICAL);
// Añadimos las vistas al objeto vertical
vertical.addView(imageViewDinamicoArriba);
//vertical.setOnClickListener(this);
vertical.addView(imageViewDinamicoAbajo);
vertical.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// I Tryed with every metods of View
Log.i("galeria", "Imagen: " + v.getId());
}
});
// Add vertical Layout to horizontal Layout
layoutDinamicoHorizontal.addView(vertical);
} // End for
} // End onCreate
#Override
public void onClick(View v) {
}
} // End Activity
imageViewDinamicoArriba.setTag(new Integer(i)) or
imageViewDinamicoAbajo.setTag(new Integer(i))
Then you will get your index in your Log.i("galeria", "Imagen: " + v.getTag());
int index = (Integer) v.getTag();
When you create a View dynamically, the id isn't added by default. If you want to use the ids to filter you should add the id manually:
imageViewDinamicoArriba.setId(i);
For more info View setId method documentation.
Hope it helps.
I want to show two views in one activity. If I clicked on button in the first view I want to see the second and other way round.
The views should not have the same size as the screen so I want e.g. to center it, like you see in first.xml.
But if I add the views with
addContentView(mFirstView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
the views are not centered. They are shown at top left.
How can I use the xml settings to e.g. center it?
first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:background="#drawable/background"
android:layout_gravity="center"
android:minWidth="100dp"
android:minHeight="100dp"
android:paddingBottom="5dp"
>
<LinearLayout android:id="#+id/head"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton android:id="#+id/first_button"
android:src="#drawable/show_second"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null" />
</LinearLayout>
second.xml same as first.xml but with
<ImageButton android:id="#+id/second_button"
android:src="#drawable/show_first"
... />
ShowMe.java
public class ShowMe extends Activity {
View mFirstView = null;
View mSecondView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFirstLayout();
initSecondLayout();
showFirst();
}
private void initFirstLayout() {
LayoutInflater inflater = getLayoutInflater();
mFirstView = inflater.inflate(R.layout.first, null);
getWindow().addContentView(mFirstView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
ImageButton firstButton = (ImageButton)mMaxiView.findViewById(R.id.first_button);
firstButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShowMe.this.showSecond();
}
});
}
private void initSecondLayout() {
// like initMaxiLayout()
}
private void showFirst() {
mSecondView.setVisibility(View.INVISIBLE);
mFirstView.setVisibility(View.VISIBLE);
}
private void showSecond() {
mFirstView.setVisibility(View.INVISIBLE);
mSecondView.setVisibility(View.VISIBLE);
}}
Hope someone can help.
Thanks
Why don't you use setContentView(R.layout.yourlayout)? I believe the new LayoutParams you're passing in addContentView() are overriding those you defined in xml.
Moreover, ViewGroup.LayoutParams lacks the layout gravity setting, so you would have to use the right one for the layout you're going to add the view to (I suspect it's a FrameLayout, you can check with Hierarchy Viewer). This is also a general rule to follow. When using methods that take layout resources as arguments this is automatic (they might ask for the intended parent).
With this consideration in mind, you could set your layout params with:
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(/* wrap wrap */);
lp.setGravity(Gravity.CENTER);
addContentView(mYourView, lp);
But I would recommend setContentView() if you have no particular needs.
EDIT
I mean that you create a layout like:
~~~/res/layout/main.xml~~~
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="....."
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
then in your onCreate() or init...Layout():
setContentView(R.layout.main);
FrameLayout mainLayout = (FrameLayout)findViewById(R.id.mainLayout);
// this version of inflate() will automatically attach the view to the
// specified viewgroup.
mFirstView = inflater.inflate(R.layout.first, mainLayout, true);
this will keep the layout params from xml, because it knows what kind it needs. See reference.
I want to add views on click of button. My screen has a text view and an edit text and a "Add More" button. on the click of button another set of text view and edit text should get appended to the screen. I am also planning to add scroll view once the my screen grows longer.
My Code snippet is as follows
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
text.setText("hello how are you?"); //this is just an example, I may want to add lot more here.
linearLayout.addView(text);
setContentView(linearLayout);
}
I know I am missing something very basic but I do not know what is that. :(
Please help.
First of all, you need to initialize each TextView with a reference to the context. So, in your onClick, given that it is in MyActivity.java:
public void onClick(View v) {
TextView text = new TextView(this);
text.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT); // Or what you decide
text.setText("Your text");
linearLayout.addView(text);
}
Second, given that you have a call to setContentView in onCreate which also adds your linearlayout to the view, you do not need to call setContentView(linearLayout) each time the button is clicked.
you should first create a new TextView and EditText add it to the linearLayout using linearLayout.addView(). No need to call setContentView() you probably already added it.
This One help you
In your XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myMainRelativeLayout"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="47dp"
android:text="Add Button" />
And your Java file Like
public class MainActivity extends Activity implements
android.view.View.OnClickListener {
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnAdd) {
RelativeLayout rl = (RelativeLayout)findViewById(R.id.myMainRelativeLayout);
Button btn = new Button(this);
btn.setId(1234);
btn.setText("Add Button Runtime");
btn.setOnClickListener(this);
rl.addView(btn);
}
if(v.getId() == 1234)
{
Toast.makeText(getApplicationContext(), "This is Your New Button", Toast.LENGTH_LONG).show();
}
}
}
This one just example you can add any view like this