Adding button when list is empty - android

I am trying to add the button dynamically when list is empty i.e no data to populate the list. I tried the below code and it not working
public class TableDemoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
Button test = new Button(this);
test.setText("Hello Android");
test.setId(5);
test.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(test);
}
}
Here is the layout file contents
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:id="#+id/TblLyt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow
android:id="#+id/AcctHeader"
>
</TableRow>
<ExpandableListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/BankExpandableListView"
android:layout_width="fill_parent"
android:layout_height="443dp"
android:layout_weight="1.32"
>
</ExpandableListView>
</TableLayout>
</LinearLayout>

You can put your button in xml layout file and do visible & invisible as per your condition
if(your condition)
{
button.setVisibility(View.VISIBLE);
}
else
{
button.setVisibility(View.GONE);
}

I solved your problem. Follow these steps. Your code is right but you have made a small mistake. You are adding your view or button in linear layout but your table layout is holding the entire area of your screen by using width and height being fill parent, so just add your button in table layout like this:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
public class TableDemoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
TableLayout table=(TableLayout) findViewById(R.id.TblLyt);
Button test = new Button(this);
test.setText("Hello Android");
test.setId(5);
test.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
table.addView(test);
//linearLayout.addView(test);
}
}
Now you can add button dynamically.

It's there, you just can't see it because of this:
<TableLayout
android:id="#+id/TblLyt"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
You are telling table to fill the entire layout. You could set the TableLayout to GONE and then add the button, or you can change the layout_height to wrap_content.

Related

Show Layout from behind another layout with animation

I have a clickable TextView:
width = match_parent, height = "wrap_content"
When I press it, I want to show a LinearLayout containing 3 views, orientation vertical, and I want to animate it to slide down from behind the TextView, below it. Like a drop-down, but not using Spinner.
Any ideas?
If you want a dropdown-like effect, you should probably use a PopupWindow to show your LinearLayout. That's what Spinner uses internally. You can set the enter and exit animations for it. By default, a PopupWindow from a Spinner performs a scale and alpha animation at the same time.
There is also PopupMenu which is a specialized class to show menus with the standard animations.
1. Create an animation XML for slide down in /res/anim/ folder:
slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="1000"
android:fromYDelta="0%"
android:toYDelta="25%" />
</set>
FYI, You can change animation duration and YDelta as per your needs.
2. Design your desired layout. Use RelativeLayout as root and set child LinearLayout visibility GONE.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<LinearLayout
android:id="#+id/layout_dropdown"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:orientation="horizontal"
android:background="#android:color/holo_red_dark"
android:visibility="gone">
<!-- Your 3 Views here -->
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Click Here"
android:textSize="30sp"/>
</RelativeLayout>
3. In your Activity, programmatically apply slide_down animation on LinearLayout(layout_dropdown) to show and sliding down when clicked on TextView(textView):
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
linearLayout = (LinearLayout) findViewById(R.id.layout_dropdown);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Animation slideDown = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down);
linearLayout.setVisibility(View.VISIBLE);
linearLayout.startAnimation(slideDown);
// Required to keep layout stay at final position after animation
slideDown.setFillAfter(true);
}
});
}
}
OUTPUT:
Hope this will help~
Make LinearLayout with scaleY=0 and then animate it to 1.0
Execute this in the onClicklistener:
ViewCompat.animate(yourView)
.scaleY(1.0f)
.start();

Android use RelativeLayout Programmatically

I have a basic app working, but now I am focusing on formatting the app and running into difficulty laying things out as I want them.
I have a list of images that the user can switch from one to the next with using a next button. Both the images and the next button are added programmatically to the page (I clear out anything in the layout, and then add the ImageView and Button). Now, instead of laying them out one on top of the other, I am trying to lay them out next to each other, so the image will take up most of the space, and then the next button will be to its right.
Looking through the documentation I was leaning towards using a RelativeLayout to accomplish this. However, I ran into some questions while using RelativeLayouts programmatically.
Activity.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout
android:orientation="vertical"
android:id="#+id/activity_training_package_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="com.example.xxx.PackageActivity"
tools:ignore="MergeRootFrame">
</RelativeLayout>
</ScrollView>
Attempt to programmatically add the button:
public void addNextButton(final int currentFile, final RelativeLayout layout) {
Button next = new Button(this);
next.setWidth(100);
int id = layout.getChildAt(0).getId(); // the image is the only thing there
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.RIGHT_OF, id);
next.setLayoutParams(lay);
next.setText("NEXT >>");
next.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
showNextFile(currentFile, layout);
}
//layout.setLayoutParams(lay);
layout.addView(next);
...
I am just wondering which LayoutParams I am supposed to be setting for this, the LayoutParams of the layout, or of the view? When I try to set it to the layout, I get a cast exception (it is expecting a FrameLayout.LayoutParams, not a RelativeLayout.LayoutParams for some reason).
Could someone please point me in the right direction to figure out how layouts are used? I cannot seem to find resources that explain which LayoutParams I should be setting.
TL;DR How do you use RelativeLayouts and LayoutParams programmatically?
The simplest solution is to use the HorizontalSrollView with a LinearLayout.
activity_test.xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
TestActivity.java
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
String next = getResources().getString(R.string.next);
for(int i=0;i<5;i++){
ImageView imgView = new ImageView(mActivity);
imgView.setLayoutParams(params);
imgView.setImageResource(R.drawable.photo);
container.addView(imgView);
Button button = new Button(mActivity);
button.setLayoutParams(params);
button.setText(next);
container.addView(button);
}
}
}
set Linear Layout weight Property in your XML file and assign weight to the imageview and button
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1" />
MainActivity.java
package com.example.stackoverflowdemos;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TableLayout;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
//Dynamically generate imageview and button
ImageView imgView = new ImageView(this);
imgView.setLayoutParams(new TableLayout.LayoutParams(0, LayoutParams.FILL_PARENT, .2f)); //set imageview height and width using weight
imgView.setImageResource(R.drawable.ic_launcher);
container.addView(imgView);
Button button = new Button(this);
button.setLayoutParams(new TableLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, .8f)); //set Button height and width using weight
button.setText("next");
container.addView(button);
}
}

Adding button in preferencescreen added in xml folder [duplicate]

Is there any way to add a button to the bottom of preferences screen and make them work correct when scrolling?
There is another solution for customizing the appearance of the preferences.
Design a normal XML layout with buttons or whatever you want to add to the standard preferences. Include a ListView in your layout and give it the ID #android:id/list.
Let's say we call the layout file res/layout/main.xml. It could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:text="This is a button on top of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
In your PreferenceActivity, add these two lines to your onCreate:
addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.main);
The ListView in your layout will then be replaced by the preferences defined the usual way in res/xml/preferences.xml.
I know this is a bit late, but I just found a solution i like better than Max's praised solution.
You can simply add a footer (or if you like the button to be on top, a header) to the PreferenceActivity's ListView like so:
public class MyActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListView v = getListView();
v.addFooterView(new Button(this));
}
}
I hope this helps someone.
This example below will render a button at the bottom of the page (in case anybody is still interested).
In case of a LinearLayout you could also apply weights; this is needed because the Listview is set to *fill_parent*.
I usually do this by adding *android:layout_weight* 's:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="10"/>
<Button android:text="This is a button on top of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"/>
</LinearLayout>
The explanation below isn't propbably 100% but it will help you understand...
+-- View Port (linear layout)
| +-- List View (this is where the preferences will go)
| |
| |
| +--
+--
+--
| Button (which was pushed out of view by the fillparent of ListView
+--
You could also say, because the Button has no weight; the button is rendered at 0dp height.
Now with the layout_weigths added it will lett the button render inview
+-- View Port (linear layout)
| +-- List View (this is where the preferences will go)
| |
| |
| +--
| +--
| | Button (which was pushed out of view by the fillparent of ListView
| +--
+--
Actually, there is a solution. Here is a code, i hope, this will be useful for anyone.
It looks like 3 options and 2 buttons in the bottom of the screen, independent of screen resolution (was targeted to 240 as lowest)
package com.myapplication.gui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import com.myproject.general.HeightListView;
import com.myapplication.R;
public class FilterActivity extends PreferenceActivity {
private LinearLayout rootView;
private LinearLayout buttonView;
private Button buttonDone;
private Button buttonRevert;
private ListView preferenceView;
private LinearLayout gradientView;
private ScrollView scrollRoot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int height = display.getHeight();
int width = height > 240 ? display.getWidth() : display.getWidth() - 4;
scrollRoot = new ScrollView(this);
scrollRoot.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
rootView = new LinearLayout(this);
rootView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
rootView.setOrientation(LinearLayout.VERTICAL);
buttonView = new LinearLayout(this);
buttonView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
buttonView.setOrientation(LinearLayout.HORIZONTAL);
buttonView.setGravity(Gravity.BOTTOM);
gradientView = new LinearLayout(this);
gradientView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
gradientView.setOrientation(LinearLayout.HORIZONTAL);
gradientView.setBackgroundResource(R.drawable.gradient);
gradientView.setPadding(0, 5, 0, 0);
gradientView.setBackgroundResource(R.drawable.gradient);
buttonDone = new Button(this);
buttonDone.setText(R.string.filterButton_Done);
buttonDone.setLayoutParams(new LayoutParams(width/2, LayoutParams.WRAP_CONTENT));
gradientView.addView(buttonDone);
buttonRevert = new Button(this);
buttonRevert.setText(R.string.filterButton_Revert);
buttonRevert.setLayoutParams(new LayoutParams(width/2, LayoutParams.WRAP_CONTENT));
gradientView.addView(buttonRevert);
buttonView.addView(gradientView);
preferenceView = new HeightListView(this);
preferenceView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
preferenceView.setId(android.R.id.list);
PreferenceScreen screen = createPreferenceHierarchy();
screen.bind(preferenceView);
preferenceView.setAdapter(screen.getRootAdapter());
rootView.addView(preferenceView);
rootView.addView(buttonView);
if (height > 240) {
this.setContentView(rootView);
}
else {
scrollRoot.addView(rootView);
this.setContentView(scrollRoot);
}
setPreferenceScreen(screen);
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
PreferenceScreen pref1 = getPreferenceManager().createPreferenceScreen(this);
pref1.setKey("pref1");
pref1.setTitle("Title");
pref1.setSummary("Summary");
root.addPreference(pref1);
PreferenceScreen pref2 = getPreferenceManager().createPreferenceScreen(this);
pref2.setKey("pref2");
pref2.setTitle("Title");
pref2.setSummary("Summary");
root.addPreference(pref2);
PreferenceScreen pref3 = getPreferenceManager().createPreferenceScreen(this);
pref3.setKey("pref3");
pref3.setTitle("Title");
pref3.setSummary("Summary");
root.addPreference(pref3);
return root;
}
}
You just need to use PreferenceFragment inside general Activity and add the button into activity layout.
public class SettingActivity extends Activity {
UserProfileViewModel userProfileViewModel = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
getFragmentManager().beginTransaction()
.replace(R.id.content, new SettingsFragment())
.commit();
}
private class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_main);
}
}
}
SettingActivity.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/buttonSave"/>
<Button
android:id="#+id/buttonSave"
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
activity_setting
It is also possible to add Action buttons to the action bar for an android standard approach.
public class PrefActivity extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.preference_header_menu, menu);
return super.onCreateOptionsMenu(menu);
}
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_add"
android:icon="#drawable/ic_menu_add_dark"
android:title="#string/menu_action_add_title"
android:showAsAction="always" />
</menu>
This would be what the code looks like in the activity at the ronny's example.
My intent was to put an menu in the bottom side of the screen.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prefs);
addPreferencesFromResource(R.xml.prefs);
/* LayoutInflater CX = getLayoutInflater();
CX.inflate(R.layout.main,null);*/
// TODO Auto-generated method stub
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="#dimens/listview_height" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="This is a button on top of all preferences." />
</RelativeLayout>
I reference #Ronnie, use RelativeLayout and set a height for layout_height of listview, and then set the button's layout_alignParentBottom = "true", It can render a button at the bottom of PreferenceScreen;
then use the way of #Max. it works for my needs.
The following is a simple solution to add a clickable button to your preference screen. This is made easy because the preferences already reserve the space in the android:widgetLayout and the button can pass clicks with android:onClick.
First create a button.xml with the content
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="BUTTON"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onButtonClick"/>
</LinearLayout>
Now in your preferences.xml, add the preference
<Preference
android:key="button"
android:title="Title"
android:summary="Summary"
android:widgetLayout="#layout/button" />
Your PreferenceActivity now only has to contain a onButtonClick member
public class MainActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main_preferences);
}
public void onButtonClick(View v) {
Log.d("Button", "Yeah, button was clicked");
}
}
preferences.xml:
<Preference
android:key="clearAllData"
android:title="#string/settings_clear_all_data">
</Preference>
SettingsFragment.java:
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference clearAllData = (Preference) findPreference("clearAllData");
// setup buttons
final Context context = getActivity();
clearAllData.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
...
}
}
}
Custom view in Preference Activity
this will help to add custom view in PreferenceActivity in Android.
Create main.xml, the only necessary view is a ListView, with id: android:id="#android:id/list".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:weightSum="1">
<ListView
android:id="#android:id/list"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="0dp">
</ListView>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create CustomPreferenceActivity.java
public class CustomPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addPreferencesFromResource(R.xml.settings);
//setup any other views that you have
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("View Added");
}
}
I found all of the above answers to be un-usable as any layouts I created to 'wrap' the PreferenceScreen container inside custom layouts (then adding a button below the ListView) didn't actually work.
They only overlaid the custom layout on top of the preferences list (floating), and clicking (e.g.) a new custom button would only invoke the preference underneath the button.
However, I found this solution which works a treat for adding a button below the preferences list container, when using PreferenceFragment.

Still Can't Add Button to Layout in Android

I just started android and I tried below questions to get this answer before posting it here:
Android - Adding layout at runtime to main layout
Add button to a layout programmatically
Dynamically adding a child to LinearLayout with getting each child's position
And I am still not able to add a button to linear layout :(
Below is the code for activity, please let me know where I am wrong:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.activity_main, null);
Button btn = new Button(this);
btn.setId(123);
btn.setText("Welcome to WI FI World");
layout.addView(btn);
}
And xml looks like below:
<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" >
</LinearLayout>
Try assigning an id to your layout then add the button to the layout.
Im pretty sure those 2 layouts are not the same, so you are infact adding a button to a layout that is never displayed.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.lnr_main);
Button btn = new Button(this);
btn.setId(123);
btn.setText("Welcome to WI FI World");
layout.addView(btn);
}
With Layout assigned an id
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lnr_main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
Take the Id for LinearLayout in XML and in jave code use that id of LinearLayout from 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:id="#+id/linear" >
</LinearLayout>
In onCreate():
LinearLayout linear=(LinearLayout)findViewById(R.id.linear);
//Select widgets
linear.addView()
Give an id to your linearLayout.
Then in your code
LinearLayout layout = (LinearLayout)findViewById(R.id.given_id);
Keep the rest the same, should work.

How to layout Array of buttons to fit in any screen size

I have created an array of buttons for my app. Now I am not able to manage the layout of these array of buttons. As a result of this, whenever I add image or change width of the buttons it's going out of the horizontal screen of the device. So is there any way to manage these Array of buttons so that they can fit in any screen size.
Here is my code:
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/liVLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:id="#+id/liVLayout1"
android:orientation="vertical"
android:layout_below="#+id/liVLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="All Contacts"
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:background="#808080">
</TextView>
</LinearLayout>
</RelativeLayout>
Java:
public class CalenderForm extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createCalender();
}
public void createCalender()
{
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams
(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
Button[][] buttons = new Button[6][7];
int count=43;
for (int i = 0; i<6; i++)
{
if(count%7==1)
{
rowLayout = new LinearLayout(this);
layoutVertical.addView(rowLayout,p);
count=count-7;
}
for(int j=0;j<7;j++)
{
buttons[i][j]=new Button(this);
buttons[i][j].setBackgroundResource(R.drawable.icon);
rowLayout.addView(buttons[i][j], p);
}
}
}
}
Snapshot before inserting image:
Snapshot before inserting image:
I know this doesn't directly answer your question, but I just want to help you out. If you're building a calendar app, creating lots of buttons really isn't the way to go:
You will have problems on different ROMs because of skins, etc.
You will not have full control over the layout (again because of the skins)
You will run into spacing issues
You will allocate a lot of memory (lots of Button objects, etc.) which will cause your app to be slow.
What I recommend is implementing your own custom View. I recently worked on a calendar app myself and tried using a GridView for the month, and that really didn't work out well (although it looked like it would), so I ultimately created my own View, which worked out perfect.
What I found very useful was Android's default, open source Calendar app. You'll find source code in there for both a month view and a day / week view (with an hour scale, etc.).
You could try a TableLayout and set the columns wrappable:
Found a nice tutorial with examples -> Android TableLayout Tutorial
To make a column wrappable (to reduce it’s width and wrap it’s content if other columns in the table are taking too much space and pushing some columns off the screen), use setColumnShrinkable to mark it shrinkable.
sounds promising
just replace this code.use weightsum property of linear and layout_weight of buttons.
package com.android.manager;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createCalender();
}
public void createCalender()
{
LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout=null;
Button[][] buttons = new Button[6][7];
int count=43;
**LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT,1);**
for (int i = 0; i<6; i++)
{
if(count%7==1)
{
rowLayout = new LinearLayout(this);
**rowLayout.setWeightSum(7);**
**layoutVertical.addView(rowLayout,param);**
count=count-7;
}
for(int j=0;j<7;j++)
{
buttons[i][j]=new Button(this);
buttons[i][j].setBackgroundResource(R.drawable.icon);
**rowLayout.addView(buttons[i][j],param);**
}
}
}
}

Categories

Resources