Adding button in preferencescreen added in xml folder [duplicate] - android

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.

Related

Android Studio Activity Layout Changing

I need help in changing layout of Activity in Android Studio when I click on button.
But I don't want to open new activity I want to change layout and design completely on the current activity by clicking button. Is it possible ?
you can inflate another layout during button click:
public class LayoutInflateDemo extends Activity {
private LinearLayout layoutToAdd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_existed);
layoutToAdd = (LinearLayout) findViewById(R.id.existedlayout);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = LayoutInflater
.from(getApplicationContext());
View view = inflater.inflate(R.layout.layout_toinfliate, null);
//Add the inflated layout to your existing view
layoutToAdd.addView(view);
}
});
}
}
layout to inflate Xml:
<?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">
<TextView
android:id="#+id/mytext"
android:text="Inflated layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
And this is your existing layout:
<?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:id="#+id/existedlayout"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clicck to inflate view"
android:id="#+id/button"
/>
</LinearLayout>
Yes it is possible by using setContentView() method. But you have to make sure that you didn't use any view (e.g. view by id) that is not available on current layout.
Best way is Fragments and FragmentActivity https://developer.android.com/guide/components/fragments.html

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);
}
}

Get element from Sliding Menu

I defined a layout view in a .xml file called menu_list_slide_lateral.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_menu_slide"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnSliBebe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/bebe" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/foto_diario" />
<Button
android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/consejos" />
<Button
android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ajustes" />
</LinearLayout>
Im creating the SlidingMenu from code:
setBehindContentView(R.layout.menu_list_slide_lateral);
setSlidingActionBarEnabled(true);
slideMenu = getSlidingMenu();
slideMenu.setMode(SlidingMenu.LEFT);
slideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slideMenu.setShadowWidthRes(R.dimen.shadow_width);
slideMenu.setBehindOffset(100);
slideMenu.setFadeDegree(0.35f);
And mi activity extends from SlidingFragmentActivity:
public class TimelineActivity extends SlidingFragmentActivity
It shows perfectly the menu, but i want to do some actions when the user chooses an option from the menu:
For example, i want to open another activity when i choose the "Bebe" option.
I tried to set a onClick event to that button but it doesn't seem to work, it makes nothing:
inflater = getLayoutInflater();
item = inflater.inflate(R.layout.menu_list_slide_lateral, null);
btnSliBebe = (Button) item.findViewById(R.id.btnSliBebe);
btnSliBebe.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Log.e(TAG, "boton bebe");
}
});
How can i access that buttons and asign them a event?
Thanks!
What you should to is to create separate fragment for slide menu which will contain your layout R.layout.menu_list_slide_lateral and will handle actions. This is easy to do.
Now when you have this fragment you need to insert it into your slide activity.
setBehindContentView which you used is placeholder for menu. So create simple layout which will hold your menu fragment. E.g. call it R.layout.menu_frame and it should be like this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Then in your sliding activity set R.layout.menu_frame as behindContentView and add your menu fragment into this view.
public class BaseSlidingActivity extends SlidingFragmentActivity {
protected MenuFragment mSlidingMenuFragment;
private SlidingMenu mSlidingMenu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the Behind View
setBehindContentView(R.layout.menu_frame);
//if we create new menu - create new MenuFragment and insert it into
//menu_frame
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mSlidingMenuFragment = new MenuFragment();
t.replace(R.id.menu_frame, mSlidingMenuFragment);
t.commit();
}
//if activity was restored(e.g. on orientation change) find it in fragment
//manager
else {
mSlidingMenuFragment = (MenuFragment) this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
}
// customize the SlidingMenu
mSlidingMenu = getSlidingMenu();
mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width);
mSlidingMenu.setShadowDrawable(R.drawable.shadow);
mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
mSlidingMenu.setFadeDegree(0.35f);
mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
}
I hope it helps. You can browse through source code of example at github slidinfmenu example

Adding button when list is empty

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.

dynamic number of gui elements in Android?

I want to create a gui application for android where the user will be able to add or remove fields of certain type (4 different type of fields) to the application. Is there a way to do so in xml?
The only way I could figure to do so is by edditing the xml file from within the app which sounds as a bad idea for me.
Hope my question is clear.
Yotam.
Edit:
I have added a simple code for direct java implantation:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
public class Leonidas extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.counter);
TextView TV = new TextView (this);
TextView UV = new TextView (this);
TV.setText("hello");
UV.setText("goof");
//setContentView(TV);
//setContentView(UV);
ViewGroup.LayoutParams lpars = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
this.addContentView(UV,lpars);
this.addContentView(TV, lpars);
this.setVisible(true);
}
}
Edit2:
I have searched for example and got the following working:
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inflater = LayoutInflater.from(this);
Button b = (Button) this.findViewById(R.id.alert);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final LinearLayout canvas = (LinearLayout)Leonidas.this.findViewById(R.id.counter_field);
final View cv = this.inflater.inflate(R.layout.counter,canvas,false);
canvas.addView(cv);
}
You can do it from within your handler too (in the implementation class).
After inflating your xml layout, you respond to some kind of user interactions.
In the handler you
either create a new View from
scratch, and specify its
layoutparams,
or inflate one using xml
After having the new view, you add it to the current (this) view, and due to its layoutparams, it will be the size, shape, color, etc. that you want.
Update:
If you'd like to add more complex views to your activity, it's better to write them in xml, and inflate them:
sample_component.xml: //inside res/layout
<?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="wrap_content" android:padding="0px">
<TextView android:id="#+id/servicename_status" android:paddingLeft="15px"
android:paddingRight="5px"
android:textStyle="bold" android:focusable="false" android:textSize="14px"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
<TextView android:id="#+id/lastcheck" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/servicename_status" />
<TextView android:id="#+id/duration" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/lastcheck" />
<TextView android:id="#+id/attempt" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/duration" />
<TextView android:id="#+id/statusinfo" android:focusable="false"
android:textSize="14px" android:layout_width="fill_parent"
android:layout_marginLeft="10px" android:layout_marginRight="3px"
android:layout_height="wrap_content" android:layout_below="#id/attempt" />
<CheckBox android:id="#+id/alert" android:focusable="false"
android:layout_alignParentRight="true" android:freezesText="false"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="5px" />
</RelativeLayout>
Inside your Leonidas activity class you have the handlers that have to respond to different user actions by adding/removing items to/from the view.
Below is a sample handler of a click event, which uses LayoutInflater, to add the sample_component.xml view to your activity:
public final class MyClickListener implements View.OnClickListener
{
private LayoutInflater inflater;
public MyClickListener()
{
inflater = LayoutInflater.from(Leonidas .this);
}
#Override
public void onClick(View v)
{
// TODO: change RelativeLayout here to whatever layout
// you'd like to add the new components to
final RelativeLayout canvas = (RelativeLayout)Leonidas.this.findViewById(R.id.my_canvas);
final View childView = inflater.inflate(R.layout.sample_component, canvas, false);
// TODO: Look up the 5 different signatures of the addView method,
// and pick that best fits your needs
canvas.addView(childView);
// check which button was pressed
switch (view.getId())
{
case R.id.btn_prev:
//handler for the prev button
break;
case R.id.btn_next:
//handler for the next button
break;
default:
break;
}
}
}
Note, that MyClickListener is implemented as an inline class within your Leonidas activity, thay's why for the context parameter it is used: this.Leonidas.
Update
The R.id.my_canvas would be the id of the view that you want to add components to. it is in your main.xml (or whatever xml you use for your Leonidas view).
If you put the MyClickListener class inside your Leonidas.java class (declare as inline class), it will recognize it.
Instead of specifying elements in the XML, you can create them dynamically and add it to the UI. This is demonstrated in the Android Hello World Tutorial here.

Categories

Resources