XML layout via program - Android Software Development

Based on user input, I have to add x number of buttons to a xml file. I have the file hard-coded now and it works, but I need to add the buttons via the program. Do I have to create the ENTIRE xml file via code?
Here is a snippet..actually, the Button and TextView are what I have to create on-the-fly x number of times.
Code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
<TableLayout
android:id="@+id/myTblId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TableRow>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person1"
android:text="Rick"
android:onClick="onClick"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10px"
android:id="@+id/item1"
/>
</TableRow>
Thanks in advance

You can just add the individual views from within your code. To help identify them, you can use the tag feature. I.e. make the first button's tag "b1", etc.

Well, I got the program to create 2 buttons for me. I don't want to use setID because it's just an int and I don't want to do case statements on "case 1: case 2: yada, yada"...it's too confusing. So, in the code below, I use setTag. However my onClick method is not working when I click on a button.
Code:
for(int i = 0; i < numDrivers; i++) {
Button button = new Button(this);
button.setTag("driver" + i+1); // should be "driver1"
button.setText(driverList.get(i));
button.setClickable(true);
button.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
table.addView(button);
}
And if I try Toast.makeText(this, driver1.getTag().toString(), Toast.LENGTH_SHORT).show(), I get a FC.

Got 2 buttons created dynamically, and they both work with onClick(), but...
There has got to be a way to assign a meaningful name to the button. Each row I have will have the button (setID 1), and 3 textviews (setId 2, 3, 4). Then another row with ID's of 5, 6, 7, 8. Yeah buddy, coding case statements for that is easy.
I know I can probably set a resource file of some type, but this is still all dynamic. I don't know if I'm going to have 2 rows or 100 until runtime.
I was looking at setTag where I can put a meaningful name in, but you can't do a switch statement with onClick(View v), switch (v.getTag) because getTag returns an Object.
Guess I'll have look into Objects because I can't possibly program "case 29:" and have any idea what the hell 29 represents LOL
Worse comes to worse to get this done (client deadline for test run is 3/22) I'll just hardcode 50 "rows" into my XML file and and preface the specs at "Maximum 50 entrants".
Which may be a good thing, because for this client, they won't go over that. But to make some mods and make this app usable in other venues, I might need over 50.

I use a dynamically generated table of buttons in the app I'm working on. You can set the X and Y size and it will create a grid of ImageButtons. The way that I did it was instead of trying to fiddle with generating them in XML, I made the XML up to the TableLayout that contains the buttons and then from there went on to create them in the java code itself. the code for the MainGame.java file which declares all of this is as follows:
Code:
package com.freekyfrogy.treasure;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.freekyfrogy.treasure.R.drawable;
public class MainGame extends Activity implements OnClickListener {
static int X, Y = 5;
static int numChests = 8;
int scoreCount = 0;
final int NUM_SWAPS = 10000;
TableLayout mainTable;
TableRow[] row = new TableRow[Y];
ImageButton[][] button = new ImageButton[X][Y];
ImageView treasure;
TextView score;
int buttonType[][] = new int[X][Y];
int sand = R.drawable.sand;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
treasure = new ImageView(this);
treasure.setBackgroundResource(R.drawable.treasure);
treasure.setVisibility(8);
mainTable = (TableLayout) findViewById(R.id.mainTable);
score = (TextView) findViewById(R.id.scoreCount);
shuffle();
makeButtons(mainTable);
}
public void shuffle() {
int loops = 0;
for(int y=0; y<Y; y++){
for(int x=0; x<X; x++){
loops++;
if(loops<=numChests){
buttonType[x][y] = 1;
}
else{
buttonType[x][y] = 0;
}
}
}
Random generator = new Random();
for (int i=0; i<NUM_SWAPS; i++){
int x1 = generator.nextInt(X);
int y1 = generator.nextInt(Y);
int x2 = generator.nextInt(X);
int y2 = generator.nextInt(Y);
//swap
int temp = buttonType[x1][y1];
buttonType[x1][y1] = buttonType[x2][y2];
buttonType[x2][y2] = temp;
}
}
public void makeButtons(View v){
int id = 0;
for(int y=0; y<Y; y++){
row[y] = new TableRow(this);
row[y].setGravity(Gravity.CENTER);
mainTable.addView(row[y]);
for(int x=0; x<X; x++){
id++;
button[x][y] = new ImageButton(this);
button[x][y].setBackgroundResource(drawable.sand);
button[x][y].setOnClickListener(this);
button[x][y].setId(id);
button[x][y].setMinimumWidth(75);
button[x][y].setMinimumHeight(75);
button[x][y].setAdjustViewBounds(true);
button[x][y].setMaxHeight(80);
button[x][y].setMaxWidth(80);
if(buttonType[x][y]==1){
button[x][y].setImageResource(drawable.treasure);
button[x][y].setColorFilter(0x00000000, Mode.CLEAR);
button[x][y].setId(id+1000);
}
row[y].addView(button[x][y]);
}
}
}
public void toast(){
Toast.makeText(this, "TOASTING YOU!!!", Toast.LENGTH_SHORT).show();
}
public void onClick(View v) {
v.findViewById(v.getId()).setBackgroundResource(R.drawable.sanddug);
if(v.getId() >= 1000){
((ImageView) v.findViewById(v.getId())).setColorFilter(0x000000, Mode.SRC_ATOP);
v.findViewById(v.getId()).setId(v.getId() - 1000);
scoreCount = scoreCount+100;
}
score.setText(Integer.toString(scoreCount));
}
}
}

Thanks for the code snippet; I'll have to look at it in more detail later on.
I have a 3/22 deadline for my app's first test run and just don't have the time to mess around with dynamic buttons. Since I know I only need 2 buttons for the test run, I've just hard-coded them into the app. Yeah, it's pretty ugly, but it's functional.

Rootstonian said:
Got 2 buttons created dynamically, and they both work with onClick(), but...
There has got to be a way to assign a meaningful name to the button. Each row I have will have the button (setID 1), and 3 textviews (setId 2, 3, 4). Then another row with ID's of 5, 6, 7, 8. Yeah buddy, coding case statements for that is easy.
I know I can probably set a resource file of some type, but this is still all dynamic. I don't know if I'm going to have 2 rows or 100 until runtime.
I was looking at setTag where I can put a meaningful name in, but you can't do a switch statement with onClick(View v), switch (v.getTag) because getTag returns an Object.
Guess I'll have look into Objects because I can't possibly program "case 29:" and have any idea what the hell 29 represents LOL
Worse comes to worse to get this done (client deadline for test run is 3/22) I'll just hardcode 50 "rows" into my XML file and and preface the specs at "Maximum 50 entrants".
Which may be a good thing, because for this client, they won't go over that. But to make some mods and make this app usable in other venues, I might need over 50.
Click to expand...
Click to collapse
You could just use if else for the tags. Or read an integer from the tag object and then execute the switch statement.
When I use dynamic linearlayouts, I add the children at a specific index and then determine which child is clicked on depending on its index.

I guess my main hurdle right now is using "setTag" vs "setID" and using setTag in a switch statement since setTag returns type Object vs. type int you get from setID.
Like I said, I'm in "panic" mode (LOL) to get my test version running by 3/22 for a live trial run. Once I get that done, I think I have a few weeks to mess around with the dynamic button creations in my TableView.
I don't think it will be too difficult, but as any programmer knows when they are up against a deadline, you have to cut some corners to get a working model without all the bells and whistles
My main bottleneck now is that for each button down the left side, and depending on which order they are hit, I have to redo the layout and put the buttons with labels AND the row data associated with that button in the order in which they were hit. Yeah, fun stuff...thank the maker for databases!

Related

[GUIDE] Clearable EditTexts

Hello everyone,
As most of you probably have, I have been working on an app that lets users input text in an EditText. However, this app possibly gets a lot of input from the user, which can lead to multiple lines of text in either of two EditTexts!
Naturally, this can result in some real headaches: when you want to clear the EditText, you'll have to delete character after character from it.
So, I decided to go on a quest. Hunt down a solution that's fat, easy to implement and works nicely from the user's prespective. Of course, it'd be nice if it looks cool, too.
This is where I came across a blog post, after some browsing of StackOverflow, that detailed a nice and quick fix.
Today, I will be explaining to all of you how to implement this, and even add a couple of little extras.
Step 1: Creating the custom View's XML layout
The first thing you have to do, since this is a custom View, is create its XML layout. Luckily, this isn't too hard:
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/clearable_edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="35dip" />
<Button
android:id="@+id/clearable_button_clear"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dip"
android:background="@drawable/ic_clear" />
</RelativeLayout>
Some explanation: This is just a layout declaration. Later on, when making the ClearableEditText constructor, you'll have to call upon the elements in this layout.
Step 2: Making the class
To create an own new View, you have to extend from one of the standard View classes. Since you are including a Button and EditText in the one (creating a compound View), RelativeLayout is a good choice.
In the constructors of the class - which overrides the stock EditText constructors - is where you inflate the layout, which has been done by adding a method initViews().
The method to pay attention to here is showHideClearButton. An addTextChangedListener call is made, which conveniently takes a TextWatcher as its parameter. That means we can easily see when something about the input changes, and act upon it.
Some methods have to be implemented, but onTextChanged is the only one we'll really need. Here, we can check the length of the String that's been entered, and see whether to hide or show to cross Button for clearing the EditText.
The code speaks for itself from here on out:
Code:
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class ClearableEditText extends RelativeLayout {
LayoutInflater inflater = null;
EditText edit_text;
Button btn_clear;
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initViews();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initViews();
}
public ClearableEditText(Context context) {
super(context);
initViews();
}
void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clearable_edit_text, this, true);
edit_text = (EditText) findViewById(R.id.clearable_edit);
btn_clear = (Button) findViewById(R.id.clearable_button_clear);
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
clearText();
showHideClearButton();
}
void clearText() {
btn_clear.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
edit_text.setText("");
}
});
}
void showHideClearButton() {
edit_text.addTextChangedListener(new TextWatcher() {
[user=439709]@override[/user]
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() > 0)
btn_clear.setVisibility(RelativeLayout.VISIBLE);
else
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
}
[user=439709]@override[/user]
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
[user=439709]@override[/user]
public void afterTextChanged(Editable s) {
}
});
}
public Editable getText() {
Editable text = edit_text.getText();
return text;
}
}
Step 3: Using the ClearableEditText
So now, we have a (hopefully) fully functional implementation. We are still missing something, though! Of course, we haven't implemented our own solution into the code yet.
Luckily, this is very easy and takes mere seconds.
To use your ClearableEditText in a layout, simply add its full path to one of the elements, like so:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<[packagename].ClearableEditText
android:id=”@+id/edit_text_clearable”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
</LinearLayout>
See? Very easy. There is still one minor issue, though...
Step 4: Finishing touches - setting attributes
As you have probably eagerly tried, the above code should completely work and give you a working clearable EditText.
Of course, since there's no free lunch in computer science, there's a catch: no attributes can be set from your layout's XML file (the number of lines, text size, etc.).
So, I thought up a very simple way of doing this programatically, from your Java code. These supplements does take extra lines in your class' code, but will do exactly the same as their XML counterparts.
In your ClearableEditText class, to set the input type, hint and maximum number of lines, add:
Code:
public void setHint(int encode) {
edit_text.setHint(encode);
}
public void setMaxLines(int lines) {
edit_text.setMaxLines(lines);
}
public void setType(int type) {
edit_text.setInputType(type);
}
Then, in your main class, where you're calling those methods:
Code:
<editTextName>.setHint("Hello world!");
<editTextName>.setMaxLines(5);
<editTextName>.setType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
Keep in mind these are examples. The setType call will set the ClearableEditText to only receive numbers, which can be positive and negative (signed, after the sign bit in bit notation). I recommend you look up the API entry for it, or Google for it.
This can be done for - seemingly, mind - any type of attribute. I've used this for text size, number of lines, to get the text, and the above examples.
Should you have anymore questions or things to say about this, please do so!
Have fun,
bassie1995
P.S.: Big thanks to the creator of the original blog post. Thanks ab1209!

Android/Java Newbie

Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
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;
}
public void mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!

[Q] How to add function to toggle switches?

I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Makbrar3215 said:
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Click to expand...
Click to collapse
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Problem!
vijai2011 said:
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Click to expand...
Click to collapse
I did what you said. Yet I encountered a problem. Please see the attached screenshot.
When I hover over the X it says "Attribute name "public" associated with an element type "RadioButton" must be followed by the ' = '
character."
Where do I put the "="
Thanks by the way. You helped me out a lot!
you are mixing java with XML. Honestly, I suggest you start on a few beginner tutorials.
Just tell me what to do. I can't go through the guide. I need this app done by August 14.
Sent from my SGH-I337M using xda app-developers app
Bad Attitude to have. This isn't a "do my work for me" forum.
And like zalez was kind enough to point out, your putting java in xml. If you expect to make an app you need to read some beginner guides first.
you have almost a month to do it.
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Makbrar3215 said:
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Click to expand...
Click to collapse
http://developer.android.com/training/index.html
But you should probably start with generic Java 101 stuff
Set Switch status from incoming JSON data
Sorry to bump this thread after such a long time but I am facing a problem with switches myself and would appreciate some help. I have a JSON parser class which is retrieving data from a database. The retrieved info contains 'ID', 'name' and 'status' fields related to a device. I can display ID and name of each of the devices (there are several rows) using a listview but I don't know how to use the 'status' field value (it is either 1 or 0) to set an associated Switch component. I have to set the Switch associated with each listview item to ON if incoming 'status' value is 1 and set it OFF if 'status' is 0. I am lost on where to put the 'setChecked' method for every listview item. Here's the code of activity that shows these list items:
Code:
package com.iotautomationtech.androidapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ToggleButton;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
public class AllDevicesActivity extends ListActivity {
Switch mySwitch = (Switch) findViewById(R.id.switchButton);
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "external_link_removed";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "devices";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditDeviceActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllDevicesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String status = c.getString(TAG_STATUS);
int toggleValue = Integer.parseInt(c.getString(TAG_STATUS));
boolean sBool = false;
if (toggleValue == 1) {
sBool = true;
}
if (status.equals("1")) {
status = "Status: ON";
}
else {
status = "Status: OFF";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewDeviceActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDevicesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_STATUS},
new int[] { R.id.pid, R.id.name, R.id.status });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The XML file:
Code:
<RelativeLayout xmlns:android="schemas.android"
android:layout_width="fill_parent"
android:layout_height="65dip"
android:orientation="vertical"
android:layout_centerVertical="true"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:textSize="17dip"
android:layout_below="@+id/name"
/>
<Switch
android:id="@+id/switchButton"
android:layout_alignParentRight="true"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:layout_centerVertical="true"
android:textOff="OFF"
android:textOn="ON"
android:onClick="onSwitchClicked"
/>
</RelativeLayout>
I have reached thus far with the code: [attached-image]
Now I only have to set those Switches according to status values from database. I have tried putting the setChecked in doInBackground method and onPostExecute method but it doesn't work. Do I have to save all status values in an array and start a loop to set all Switches? Where would that code go?
ANY kind of help/guidance here is appreciated!

[Must see guide] Use activity as Dialog Window or Box

Have u ever thought to use the activities as a dialog box or window...
if u ever thought so then it would have been difficult for u as u might be thinking how to resize the activity window...
but its possible...
Using activities as a dialog boxes will have following benefits:-
* i have personally faced difficulties using list views in dialog boxes... but this method is super easyt..
* u can theme each dialog boxes separately in the same app...regardless of what themes u have defined in resources..
* u can add custom library views to the dialog boxes...this thing is not possible in traditional dialog boxes that android offers...
* and much things can be implemented depending upon how developer thinks...
JUST SEE HOW I HAVE IMPLEMENTED THIS IN MY OPEN SOURCED APP AT THIS THREAD...
http://forum.xda-developers.com/showthread.php?t=2547427
NOTE:- THIS GUIDE IS FOR ANDROID 4.0+
In this tutorial i will be adding "title page indicator to an activity" and use that activity as a dialog box.....
STEP 1:
Create an empty project and in .java file paste the following codes..
Code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return textView;
}
}
}
STEP 2:
Now download the "Title Page Indicator Library" and include it in your project
http://viewpagerindicator.com/
if u get any error then delete "android-support-v4.jar" from the sample project that u have created for this guide..
STEP 3:
Now open the only layout file.. and paste the following...
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:background="@android:color/darker_gray"
app:footerLineHeight="2dp"
app:footerIndicatorHeight="4dp"
app:footerIndicatorStyle="underline"
app:selectedBold="true"
android:padding="10.0dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:background="#80000000"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:layout_weight="1.0" >
</android.support.v4.view.ViewPager>
</LinearLayout>
STEP 4:
Verify the minimum sdk requirement is 14 or above...
STEP 5:
Now go to .java file
i). Create a variable of type "TitlePageIndicator" and it should look like
Code:
TitlePageIndicator indicator;
ii).Get id for indicator ...
Code:
indicator = (TitlePageIndicator)findViewById(R.id.indicator);
iii).Add view to indicator
Code:
indicator.setViewPager(mViewPager);
iv).Till now we have created the simple activity including title page indicator ..now comes trickiest part..
go to line below the setContentView(R.layout.activity_main);
Type the following codes...
Code:
WindowManager.LayoutParams params = this.getWindow().getAttributes();
params.width = 400;// setting the width of the dialog box
params.height = 500;// setting the height of the dialog box...
//params.(......) much more explorations can be done...
STEP 6: (OPTIONAL)
If u want to do theaming and all to the dialog box read my thread about adding different transparency level to activity that can be applied to this dialog boxes also..
http://forum.xda-developers.com/showthread.php?p=46964005#post46964005
NOW DONE AND FINALLY COMPILE IT AND RUN IT...
For better understanding i m attaching the same sample project...
i hope it helped u and dont forget u see my app(open source app) that uses dialog boxes created using this method...

how to set the itemHeight on listView

I am using the following code to add custom items in a listView. I can set the textColor, backgroungColor and so on, but I cannot set the item height. I want it to be smaller than the listView default.
This is the item class:
Code:
class Adapter2 extends ArrayAdapter<String> {
public Adapter2(Context context, int resID, int items) {
super(context, resID, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setMaxHeight(5);
((TextView)v).setHeight(5);
((TextView)v).setMinHeight(5);
((TextView)v).setTextColor(Color.WHITE);
return v;
}
}
and this is how I use it:
Code:
Adapter2 ad;
ad= new Adapter2(this, android.R.layout.simple_list_item_1,0);
ad.add(data); //data is a short string (less than 10 characters)
list.setAdapter(ad);
and the code for my listView is:
Code:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/history"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/stanga"
android:layout_toLeftOf="@+id/switch1"
android:layout_alignParentTop="true"
android:paddingTop="0dp"
android:padding="0dp"
android:paddingBottom="0dp"
android:dividerHeight="0px"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingEnd="0dp"
android:paddingStart="0dp"
android:scrollingCache="false"/>
How could I change the item height?
I have also changed the padding values (in design) and the View height(in java) but I didn't see any change at all.
Thank you in advance.
I have tried your answer arpitkh96 but it didn't solve anything.
I have solved the problem by adding negative values for the dividerHeight in xml and changing it's metrics from px in sp.
Change values of layout_height of listview(in xml) from wrap_content to some value such as 40.0dip
Sent from my GT-S5570 using XDA Premium 4 mobile app
Approach to take for custom view look and dimensions
You would use a custom adapter like this and for the "txtViewRID" (note does'nt need to be a text view can be any view) resource you would change it to an xml (of your custom list view height)
Once created use listview.setAdapter(new SearchStoreAdapter(this, [R.id.yourview], [List<DataSet>])
public class SearchStoreAdapter extends ArrayAdapter<Store> {
private ArrayList<Store> objects;
private FragmentActivity theAct;
public SearchStoreAdapter(FragmentActivity a, int txtViewRID, ArrayList<Store> aList) {
super(a, txtViewRID, aList);
this.objects = aList;
this.theAct = a;
}
.. // extra code
// get View method here
}
You can set it programmatically by changing layout parameters of convertView inside adapters getView() method

Categories

Resources