how to set the itemHeight on listView - Java for Android App Development

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

Related

[GUIDE-DEV][HTC Sense SDK, Sense 4,5,6] How to build apps for HTC Sense

Complete GUIDE to develop an application using HTC OpenSense SDK​
Requirements:
Eclipse
Basic knowledge of Android App Development. I will not explain basic things (Like making activity, listview and etc)
HTC OpenSense SDK Installed - See post 4 How to add Reference Library
HTC Phone with HTC Sense. Not For AOSP ROMs
Create Project with OpenSense SDK
Create new project. Name it as you want. These are requirements. Other you can state as you want
Minimum Required SDK - 15
Target SDK - >= 19 (or older is 16)
Compile with - HTC OpenSense API 19 (or older is 16)
Theme - Holo Light with dark action bar
Create activity - Blank
Navigation type - None
Check if SDK is choosen correctly
In your project in Android Dependencies should be HTCExtension.jar file
Above Android Dependencies should be stated which SDK api you are using. HTC OpenSense APIs [Android 4.4.2] (or older is 4.1.2)
You can start building your application with HTC OpenSense SDK.
Guide content:
Add HTC Carousel with Tabs
[*]Add 3 Dot menu to actionbar
[*]HTC AlertDialog example
[*]HTC ListView and HtcListActivity example
[*]Add HTC Sense Skin support (Only Sense 3.6 to Sense 4.1)
[*]Using HTCPreference in your App
[*]Add Sense 6 theme support to your application
[*]Add HTC's Swipe2Update to ListView
[*]Add SlidingMenu
[*]Expandable List View. Thx to DHD22800
[*]Quick tips. Thx to DHD22800
​
If I helped you to create your first Application using HTC OpenSense SDK simply rate thread and hit thanks button, give credits and link to this Thread. If you are brave enought to admitt that this thread is helped you.
In any case Im doing it to help you to learn more​
HTC Carousel Activity/Fragment (Swipeable tabs) - Sense 3.6 up to Sense 6 Samples
HTC Carousel with Tabs for Sense 3.6 up to Sense 4 (Using Activities)
Create classes and Carousel (HTC Sense Tabs)
Create simple activities
Create two classes Tab1.java; Tab2.java
Create two layout xml files - tab_1.xml; tab_2.xml;
Place any two different png icons for Tab1 and Tab2 reference
tab_1.xml
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Tab1" />
</RelativeLayout>
tab_2.xml
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Tab2" />
</RelativeLayout>
Tab1.java
Code:
package com.yourpackage.name;
import android.app.Activity;
import android.os.Bundle;
public class Tab1 extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_1);
}
}
Tab2.java
Code:
package com.yourpackage.name;
import android.app.Activity;
import android.os.Bundle;
public class Tab2 extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
}
}
Create carousel (HTC Sense Tabs) and put tabs together
Create class: TabProvider.java; Remove everything inside class and place this code:
com.yourpackage.name - it is your name of package.
TabProvider.java
Code:
package com.yourpackage.name;
import com.htc.content.CarouselProvider;
[user=1299008]@supp[/user]ressWarnings("deprecation")
public class TabProvider extends CarouselProvider {
final static String AUTHORITY =
"com.yourpackage.name.TabProvider";
public TabProvider() {
super();
setupCarousel(AUTHORITY);
}
}
Open MainActivity, remove everything from class and paste this code:
MainActivity.java
Code:
package com.yourpackage.name;
import android.content.Intent;
import android.os.Bundle;
import com.htc.widget.CarouselActivity;
import com.htc.widget.CarouselHost;
public class MainActivity extends CarouselActivity {
final static String AUTHORITY =
"com.yourpackage.name.TabProvider";
public MainActivity() {
super(AUTHORITY);
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setGId(1);
super.onCreate(savedInstanceState);
final CarouselHost mPanelHost = getCarouselHost();
mPanelHost.addTab("Tab1", this, R.string.tab_1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
(new Intent("com.yourpackage.name.Tab1")));
mPanelHost.addTab("Tab2", this, R.string.tab_2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
(new Intent("com.yourpackage.name.Tab2")));
}
}
Configuring manifest
Dont forget, all classes have to be in Manifest.
Code:
<activity
android:name=".Tab1"
android:screenOrientation="portrait"
android:configChanges="orientation"
android:label="Tab1" >
<intent-filter>
<action android:name="com.yourpackage.name.Tab1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Tab2"
android:screenOrientation="portrait"
android:configChanges="orientation"
android:label="Tab2" >
<intent-filter>
<action android:name="com.yourpackage.name.Tab2" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Also for HTC SDK you have to state Provider: Create provider at the end of Manifest before </application> tag
Code:
<provider
android:name="com.yourpackage.name.TabProvider"
android:authorities="com.yourpackage.name.TabProvider" />
Create ActionBar in HTC Sense Style
For all tabs in your main activity you dont need to create actionbar for each of them, you need only one Actionbar for all Tabs.
That means all Activities which will be part of TabCarousel it will use the same action bar from MainActivity.
Make Changes in your mainactivity as follow:
MainActivity.java with ActionBar
Code:
package com.yourpackage.name;
import android.content.Intent;
import android.os.Bundle;
import com.htc.widget.CarouselActivity;
import com.htc.widget.CarouselHost;
[COLOR="Red"]import com.htc.widget.ActionBarExt;
import com.htc.widget.ActionBarText;[/COLOR]
public class MainActivity extends CarouselActivity {
final static String AUTHORITY =
"com.yourpackage.name.TabProvider";
[COLOR="red"]public static ActionBarText mActionText;[/COLOR]
public MainActivity() {
super(AUTHORITY);
}
[COLOR="red"] private void SetupActionBar()
{
Object obj = new ActionBarExt(this, getActionBar());
((ActionBarExt)obj).setFullScreenEnabled(true);
((ActionBarExt)obj).enableHTCLandscape(false);
mActionText = new ActionBarText(this);
mActionText.setPrimaryText(R.string.app_name);
obj = ((ActionBarExt)obj).getCustomContainer();
((ActionBarContainer)obj).setRightDividerEnabled(true);
((ActionBarContainer)obj).addCenterView(mActionText);
}[/COLOR]
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setGId(1);
super.onCreate(savedInstanceState);
final CarouselHost mPanelHost = getCarouselHost();
[COLOR="red"]SetupActionBar();[/COLOR]
mPanelHost.addTab("Tab1", this, R.string.tab_1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
(new Intent("com.yourpackage.name.Tab1")));
mPanelHost.addTab("Tab2", this, R.string.tab_2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
(new Intent("com.yourpackage.name.Tab2")));
}
}
HTC Carousel with Tabs for Sense 4.1 up to Sense 5.5 (Using Fragments)
Create Carousel Fragment, Tabs, MainActivity
Create Tab Fragments
Now instead of Activities we will use Fragments, and it is difficult for some users. And I will try to explain how to build Carousel and not how to build Fragment Activity. But as example you can refer to my Open Source project myStore (which now converted to Fragments)
Create two classes Tab1Fragment and Tab2Fragment
Tab1Fragment.java
Code:
package your.package.name;
[COLOR="Lime"]#2[/COLOR] import android.app.Fragment;
[COLOR="lime"]#1[/COLOR] public class Tab1Fragment [B][COLOR="red"]extends Fragment[/COLOR][/B] {
Button button;
[COLOR="lime"]#3[/COLOR] public Tab1Fragment () {
}
[COLOR="lime"]#4[/COLOR] [user=439709]@override[/user]
public [B][COLOR="Red"]View onCreateView[/COLOR][/B](LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container, false);
[COLOR="Lime"]#7[/COLOR] button = (Button) [B][COLOR="Red"]view.[/COLOR][/B]findViewById(R.id.button);
[COLOR="RoyalBlue"][I]//All your code that you need when application is first time created (see onCreate method example)[/I][/COLOR]
[COLOR="lime"]#5[/COLOR] [B][COLOR="red"]return view;[/COLOR][/B]
}
[COLOR="lime"]#6[/COLOR]
}
As you can see the Class structure is different from what you might get used.
Now you need to extend class as Fragment (#1) and import android.app.Fragment; (#2)
Then you need to have public method which represent the entire Class with the name of the Class (#3)
And Fragment uses onCreateView method instead of onCreate in Activity (#4)
And you also need return statement for the view (#5) which will be at the end after all your code inside onCreateView method
Outside onCreateView you will have all your methods for the purpose of application and those methods you will call from onCreateView method.
Example of (#7) is that how you need to use findViewById method. you need to add view. before the method. Other than tha is the same
Now create Tab2Fragment and use the same method but different layout resources.
Create Tab Provider
Code:
package your.package.name;
import com.htc.fragment.content.CarouselProvider;
public class TabProvider extends CarouselProvider {
public TabProvider(){
super();
setupCarousel(MainActivity.AUTHORITY);
}
}
Create CarouselFragment
Now to store tabs in your application we will use separate Carousel class where you will identify each tab, name, Class, icons , etc
For each tab create method for it for example
Code:
private void addTab1(CarouselHost host, String tag, int icon, int str) {
host.addTab(getActivity(), new CarouselTabSpec(tag,
str, icon, icon, icon, Tab1Fragment.class.getName()));
}
private void addAnotherTab(CarouselHost host, String tag, int icon, int str) {
host.addTab(getActivity(), new CarouselTabSpec(tag,
str, icon, icon, icon, AnotherTabFragment.class.getName()));
}
and in onActivityCreated method add your tab as in example
Code:
addAnotherTab(host, "AnotherTab", R.drawable.another_icon,
R.string.another_tab);
Carousel.java
Code:
package your.package.name;
import android.os.Bundle;
import com.htc.fragment.widget.CarouselFragment;
import com.htc.fragment.widget.CarouselHost;
import com.htc.fragment.widget.CarouselTabSpec;
public class Carousel extends CarouselFragment {
public Carousel() {
super(MainActivity.AUTHORITY);
requestCarouselFeature(CarouselFragment.FEATURE_CUSTOM_TITLE);
}
private void addTab1(CarouselHost host, String tag, int icon, int str) {
host.addTab(getActivity(), new CarouselTabSpec(tag,
str, icon, icon, icon, Tab1Fragment.class.getName()));
}
private void addTab2(CarouselHost host, String tag, int icon, int str) {
host.addTab(getActivity(), new CarouselTabSpec(tag,
str, icon, icon, icon, Tab2Fragment.class.getName()));
}
[user=439709]@override[/user]
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final CarouselHost host = getCarouselHost();
addTab1(host, "Tab1", R.drawable.ic_tab1,
R.string.tab1);
addTab2(host, "Tab2", R.drawable.ic_tab2,
R.string.tab2);
}
}
Create MainActivity
Now MainActivity will be simple Activity with reference to Carousel class.
Code:
package your.package.name;
public class MainActivity extends Activity {
final static String AUTHORITY = "your.package.name.MainActivity";
private Carousel mCarousel = null;
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
final int rootId = 1;
FrameLayout viewRoot = new FrameLayout(this);
viewRoot.setId(rootId);
setContentView(viewRoot);
mCarousel = new Carousel();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(rootId, mCarousel);
ft.commit();
registerForContextMenu(viewRoot);
}
}
Configuration of Manifest
For Fragments you dont need anymore to add permission for them in Manifest (Only for Activities)
So basically with One mainactivity and two Tabs your manifest should look like
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name"
android:versionCode="10"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
allowSkinChange="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="your.package.name.MainActivity"
android:screenOrientation="portrait"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="your.package.name.TabProvider"
android:authorities="your.package.name.MainActivity" />
</application>
</manifest>
Make sure your provider is exaclty as follow.​
HTC Carousel with Tabs for Sense 6 (Using Fragments)
Create CarouselFragment, MainActivity, Tabs
CarouselFragment:
Code:
package com.your.pkg;
[COLOR="red"]import com.htc.fragment.widget.CarouselFragment; <!-- Make sure the imports from com.htc.fragment.*-->
import com.htc.fragment.widget.CarouselHost;
import com.htc.fragment.widget.CarouselTabSpec;[/COLOR]
importcom.your.pkg.MainActivity;
import com.your.pkg.R;
import android.os.Bundle;
public class Carousel extends [COLOR="Red"]CarouselFragment[/COLOR] {
public Carousel() {
super(MainActivity.AUTHORITY);
requestCarouselFeature(CarouselFragment.FEATURE_CUSTOM_TITLE);
}
private void addTab(CarouselHost host, String tag, int icon, int str, String tag5) {
host.addTab(getActivity(), new CarouselTabSpec(tag,
str, tag5));
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final CarouselHost host = getCarouselHost();
addTab(host, [COLOR="Blue"]"FirstTab"[/COLOR], R.drawable.ic_launcher,
R.string.[COLOR="Blue"]first[/COLOR], First.class.getName());
addTab(host, [COLOR="Blue"]"SecondTab"[/COLOR], R.drawable.ic_launcher,
R.string.[COLOR="Blue"]second[/COLOR], Second.class.getName());
[COLOR="Red"]<!-- Add as many addTab(); methods as you need Tabs. The addTab() is universal-->[/COLOR]
}
}
MainActivity
Code:
public class MainActivity extends MfMainActivity {
public final static String AUTHORITY = "mikrosmile.kontrol.MainActivity";
private Carousel mCarousel = null;
static Window window;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
final int rootId = 1;
FrameLayout viewRoot = new FrameLayout(this);
viewRoot.setId(rootId);
setContentView(viewRoot);
mCarousel = new Carousel();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(rootId, mCarousel);
ft.commit();
registerForContextMenu(viewRoot);
getWindow().setFormat(1);
}
}
Tabs
Code:
Any Activity or Fragment
HTC's Release to Refresh method (Swipe2Refresh)
The Release to Refresh is like this:
View attachment 2711413
It can be added to any View. I will show example how to add it to ListView
Code:
[COLOR="red"]import com.htc.widget.OnPullDownListener;[/COLOR]
public static ActionBarRefresh aRefresh;
@Override
protected void onCreate(Bundle bundle) {
//Adding inside onCreate method of you listActivity
list.[COLOR="Red"]setOnPullDownListener(new PullDown());[/COLOR]
}
public class PullDown implements OnPullDownListener{
//just a class inside your listActivity
@Override
public void onGapChanged(int top, int bottom) {
if(top != 0){
actionbarext.getCustomContainer().setRotationMax(top);
actionbarext.getCustomContainer().setRotationProgress(bottom);
//actionbarext.getCustomContainer is your ActionBar container
}
}
@Override
public void onPullDownCancel() {
actionbarext.getCustomContainer().setUpdatingState(0);
}
@Override
public void onPullDownRelease() {
actionbarext.getCustomContainer().setUpdatingState(0);
//do whatever you need to update the list here, you can call a method or AsyncTask from here
}
@Override
public void onPullDownToBoundary() {
actionbarext.getCustomContainer().setRotationProgress(actionbarext.getCustomContainer().getRotationMax());
}
}
Code:
On your method to update list add this to onPreExecute
aRefresh.setVisibility(View.VISIBLE);
aRefresh.setPrimaryText("Updating...");
actionbartext.setPrimaryVisibility(View.GONE);
actionbartext.setSecondaryVisibility(View.GONE);
When you finish your task to update list, inside onPostExecute add this
actionbarext.getCustomContainer().setUpdatingState(0);
Code:
Inside your method to SetupActionBar add this
aRefresh = new ActionBarRefresh(c);
aRefresh.setVisibility(View.GONE);
actionbarext.getCustomContainer().addCenterView(aRefresh);
​
Add HTC Sense 6 Theme support to your app
Inside your MainActivity add this method
Code:
public static int getHtcThemeID(Context context, int i)
{
return HtcWrapConfiguration.getHtcThemeId(context, i);
}
And in onCreate method add this
Code:
setTheme(getHtcThemeID(context, 0));
This method is returning current Choosen theme ID by Variable from 0 to 3.
So, when you open Personalization - Theme. You see 4 Themes. First 3 has different Color boxes at the top. The first 3 is the actual variable integer from 0 - 3.
So, if you want to get , let's say Red color from Theme 2. You have to Choose Theme 2 in the Theme Settings, and in the app use this:
Code:
setTheme(getHtcThemeID(context, 3));
Once you change Theme, it will also use The Orange color from Theme 1, and the Purple Color from Theme 3
​
Add SlidingMenu to your Sense application
To make the sliding menu in your application like Mail app or File manager app, follow this:
View attachment 2876504
Code:
public class MainActivity extends [COLOR="Red"]SlidingActivity [/COLOR]{
[COLOR="red"]private SlidingMenu mSlidingMenu;[/COLOR]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
window = getWindow();
setContentView(R.layout.activity_main);
[COLOR="red"]setBehindContentView(R.layout.activity_behind);
initSlidingMenu();[/COLOR]
SetupActionBar(this);
}
private void initSlidingMenu()
{
mSlidingMenu = getSlidingMenu();
[COLOR="red"]mSlidingMenu.setBehindWidth(500);[/COLOR] [COLOR="Lime"]//any width as you want[/COLOR]
mSlidingMenu.setFadeDegree(0.5F);
mSlidingMenu.setFadeEnabled(true);
mSlidingMenu.setMode(0);
mSlidingMenu.setTouchModeAbove(0);
mSlidingMenu.setOnOpenedListener(new com.htc.widget.SlidingMenu.OnOpenedListener() {
public void onOpened()
{
initSlidingMenuContent();
}
});
}
private void initSlidingMenuContent(){
[COLOR="red"] mSlidingMenu.setShadowWidth(50);
mSlidingMenu.setShadowDrawable(ICservices.getShadowDrawable());[/COLOR][COLOR="Lime"]//any shadow drawable you want
//here is all your code that represent the behind layout. it can be listview or any other View you need[/COLOR]
}
[COLOR="SeaGreen"]//if you want to have a toggle at the actionbar, also add OnClickListener to ActionbarTextView and add IconView to Actionbar[/COLOR]
}
add this permission to Manifest:
[COLOR="red"]<uses-permission android:name="com.htc.permission.APP_DEFAULT" />[/COLOR]
Add 3 Dot menu to actionbar
For the Menu in actionbar you just implement simple menu method, but you dont need to use menu.xml for it.
Also you dont need to create string values for Menu, it will generate automatically for you, the icon, and the name.
This is method to create Menu in ActionBar. Add it in MainActivity before SetupActionBar() method
Code:
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("ContextMenu");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu (Menu menu) {
menu.add(1, 1, 1, R.string.settings);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
boolean flag = true;
switch (menuitem.getItemId())
{
case 1:
startActivity(new Intent(this, Settings.class));
break;
}
return flag;
}
This is your new MainActivity with Menu
Code:
package com.yourpackage.name;
import android.content.Intent;
import android.os.Bundle;
import com.htc.widget.CarouselActivity;
import com.htc.widget.CarouselHost;
import com.htc.widget.ActionBarExt;
import com.htc.widget.ActionBarText;
[COLOR="Red"]import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;[/COLOR]
public class MainActivity extends CarouselActivity {
final static String AUTHORITY =
"com.yourpackage.name.TabProvider";
public static ActionBarText mActionText;
public MainActivity() {
super(AUTHORITY);
}
[COLOR="red"]public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("ContextMenu");
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu (Menu menu) {
menu.add(1, 1, 1, R.string.settings);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
boolean flag = true;
switch (menuitem.getItemId())
{
case 1:
startActivity(new Intent(this, Settings.class));
break;
}
return flag;
}[/COLOR]
private void SetupActionBar()
{
Object obj = new ActionBarExt(this, getActionBar());
((ActionBarExt)obj).setFullScreenEnabled(true);
((ActionBarExt)obj).enableHTCLandscape(false);
mActionText = new ActionBarText(this);
mActionText.setPrimaryText(R.string.app_name);
obj = ((ActionBarExt)obj).getCustomContainer();
((ActionBarContainer)obj).setRightDividerEnabled(true);
((ActionBarContainer)obj).addCenterView(mActionText);
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setGId(1);
super.onCreate(savedInstanceState);
final CarouselHost mPanelHost = getCarouselHost();
SetupActionBar();
mPanelHost.addTab("Tab1", this, R.string.tab_1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
R.drawable.ic_tab1,
(new Intent("com.yourpackage.name.Tab1")));
mPanelHost.addTab("Tab2", this, R.string.tab_2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
R.drawable.ic_tab2,
(new Intent("com.yourpackage.name.Tab2")));
}
}
HTC AlertDialog​
In order to have alertdialog you need to have OnClickListener and inside OnClickListener you paste alertDialog.
Code:
public void onItemClick(HtcAdapterView<?> parent, View view, int position, long id) {
[COLOR="red"]HtcAlertDialog.Builder[/COLOR] alertDialog = new [COLOR="red"]HtcAlertDialog.Builder[/COLOR]([B]YourActivity.this[/B]);
alertDialog.setTitle(R.string.title_txt);
alertDialog.setMessage(R.string.message_txt);
alertDialog.setIcon(R.drawable.icon);
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
//Do your actions here when user click Yes
}
});
alertDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Do your action here when user click No.. or just cancel dialog using follow..
dialog.cancel();
}
});
alertDialog.show();
}
As you can see Dialog is not so difficult, but need to identify exaclty which Builder you are gonna use.
YourActivity.this - means the activity where you create the dialog
You can also see available options of what you can implement inside dialog.. like 3 buttons.
Start typing alertDialog. finish with the dot and in Eclipse there will be new pop-up window and you can add some more
Also dont forget alertDialog.show(); at the end, otherwise Dialog wont shows​
HTC ListView and HtcListActivity. ​
There are two ways of implementing Htc List view. You can use Simple Activity, Fragment or just easy use HtcListActivity extension.
For full htc style you need to use Main List layout, and Details layout + List adapter.
Example using Activity
Code:
public class AboutActivity extends Activity {
[COLOR="Red"]HtcListView lv1;[/COLOR]
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_activity);
ArrayList<AboutDetails> image_details = GetSearchResults();
[COLOR="red"]final HtcListView lv1 = (HtcListView) findViewById(R.id.about_list);[/COLOR]
[user=1299008]@supp[/user]ressWarnings("unused")
lv1.setAdapter(new AboutListBaseAdapter(this, image_details));
lv1.setOnItemClickListener(new HtcAdapterView.OnItemClickListener() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
[user=439709]@override[/user]
public void onItemClick(HtcAdapterView<?> a, View v, int position, long id) {
vibrator.vibrate(50);
Object o = lv1.getItemAtPosition(position);
final AboutDetails obj_itemDetails = (AboutDetails)o;
}
});
}
private ArrayList<AboutDetails> GetSearchResults(){
ArrayList<AboutDetails> results = new ArrayList<AboutDetails>();
AboutDetails item_details = new AboutDetails();
item_details.setName(R.string.mikrosmile);
item_details.setItemDescription(R.string.mikrosmile_info);
item_details.setImageNumber(1);
results.add(item_details);
return results;
}
}
AboutDetails
Code:
public class AboutDetails {
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
public int getItemDescription() {
return itemDescription;
}
public void setItemDescription(int itemDescription) {
this.itemDescription = itemDescription;
}
public int getImageNumber() {
return imageNumber;
}
public void setImageNumber(int imageNumber) {
this.imageNumber = imageNumber;
}
private int name ;
private int itemDescription;
private int imageNumber;
}
AboutListBaseAdapter
public class AboutListBaseAdapter extends BaseAdapter {
private static ArrayList<AboutDetails> aboutDetailsrrayList;
private Integer[] imgid = {
R.drawable.mikrosmile,
};
private LayoutInflater l_Inflater;
public AboutListBaseAdapter(Context context, ArrayList<AboutDetails> results) {
aboutDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return aboutDetailsrrayList.size();
}
public Object getItem(int position) {
return aboutDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.about_htc_details, null);
holder = new ViewHolder();
holder.txt_itemName = ([COLOR="red"]HtcListItem2LineText[/COLOR]) convertView.findViewById(R.id.list_item);
holder.itemImage = ([COLOR="red"]HtcListItemTileImage[/COLOR]) convertView.findViewById(R.id.list_item_img);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_itemName.setPrimaryText(aboutDetailsrrayList.get(position).getName());
holder.txt_itemName.setSecondaryTextSingleLine(false);
holder.txt_itemName.setSecondaryText(aboutDetailsrrayList.get(position).getItemDescription());
holder.itemImage.setTileImageResource(imgid[aboutDetailsrrayList.get(position).getImageNumber() - 1]);
return convertView;
}
static class ViewHolder {
[COLOR="red"]HtcListItem2LineText txt_itemName;
HtcListItemTileImage itemImage;[/COLOR]
}
}
Layout - about_activity
Code:
<?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:background="@drawable/bg_white">
<[COLOR="red"]com.htc.widget.HtcListView[/COLOR]
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/about_list"
android:background="@drawable/common_app_bkg"
/>
</LinearLayout>
Layout - about_htc_details
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<[COLOR="red"]com.htc.widget.HtcListItemSeparator [/COLOR]
android:id="@+id/Lseparator"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
[COLOR="red"]<com.htc.widget.HtcListItem
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.htc.widget.HtcListItemTileImage
android:id="@+id/list_item_img" />
<com.htc.widget.HtcListItem2LineText
android:id="@+id/list_item" />
</com.htc.widget.HtcListItem>[/COLOR]
</LinearLayout>
HTC ListView Example by xcesco89
Add HTC Sense Skin support.
In AndroidManifest add this line inside <application tag and before first <activity tag where you have your MainActivity
Code:
<application
[COLOR="Red"]allowSkinChange="true"[/COLOR]
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.yourpackage.name.MainActivity"
There will be Error in Manifest, says "Attribute is missing the Android namespace prefix"
It is fine, to fix it go to - Project -> Clean; Choose your Application and click Ok​
Add reference library to use full HTC app experience
Sense 6
Download this package - View attachment addon-htc_opensense_apis-htc-19.zip
Place the extracted folder to <location of android SDK>\android\sdk\add-ons\
Choose HTC OpenSense SDK 19 when you start building your application. Profit
Sense 5 and below
Refer to this, thanks to Jonny
Make sure HTCExtension lib is appear in your Eclipse project​
Use HTCPreference Activity
Htc Preference is the same as normal Preference but you need to follow some rules when you want to have this.
First in your Preference activity (for example you already have one) change PreferenceActivity to HtcPreferenceActivity.
import com.htc.preference.*;
In prefs.xml (or any other xml file you have your preferences in) make sure everything is using this way
This is original android way.
<PreferenceScreen> </PreferenceScreen>
This is Htc way
<com.htc.preference.HtcPreferenceScreen> </com.htc.preference.HtcPreferenceScreen>
So basically to every single item in preferences you need to add com.htc.preference.Htc****
Here is prefs.xml example
Code:
<?xml version="1.0" encoding="utf-8"?>
<[COLOR="Red"]com.htc.preference.Htc[/COLOR]PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<[COLOR="red"]com.htc.preference.Htc[/COLOR]CheckBoxPreference
android:title="@string/load_icons"
android:summary="@string/load_icons_summary"
android:defaultValue="true"
android:key="show_dialog">
</[COLOR="red"]com.htc.preference.Htc[/COLOR]CheckBoxPreference>
<[COLOR="red"]com.htc.preference.Htc[/COLOR]SwitchPreference
android:title="@string/load_skins"
android:summary="@string/load_skins_summary"
android:switchTextOn="@string/on"
android:switchTextOff="@string/off"
android:defaultValue="true"
android:key="skins_on_start">
</[COLOR="red"]com.htc.preference.Htc[/COLOR]SwitchPreference>
</[COLOR="red"]com.htc.preference.Htc[/COLOR]PreferenceScreen>
This is how Pref activity should be
Code:
package com.yourpackage.name;
import android.os.Bundle;
import android.view.View;
import com.htc.widget.ActionBarContainer;
import com.htc.widget.ActionBarExt;
import com.htc.widget.ActionBarText;
[COLOR="red"]import com.htc.preference.*;[/COLOR]
public class Settings extends [COLOR="red"]Htc[/COLOR]PreferenceActivity {
private ActionBarExt actionBarExt=null;
private ActionBarText actionBarText=null;
private ActionBarContainer actionBarContainer=null;
private void SetupActionBar() {
actionBarExt=new ActionBarExt(this,getActionBar());
actionBarExt.enableHTCLandscape(false);
actionBarContainer=actionBarExt.getCustomContainer();
actionBarText=new ActionBarText(this);
actionBarText.setPrimaryText(R.string.settings);
actionBarContainer.addCenterView(actionBarText);
actionBarContainer.setRightDividerEnabled(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
SetupActionBar();
}
}
If you cannot import com.htc.preference.*; (Eclipse will give you error) it means you dont have HtcExtension lib. Make sure you added it before doing this.
​
Great guide! HTC Dialog isn't hard, just the same as the normal dialog, but putting Htc before the dialog stuff, right?
Looking forward to the ListView guide!
MaartenXDA said:
Great guide! HTC Dialog isn't hard, just the same as the normal dialog, but putting Htc before the dialog stuff, right?
Looking forward to the ListView guide!
Click to expand...
Click to collapse
yep dialog ist that hard.. but still need to clarify )
Subscribed ! :good:
Hai So, how could I change the tab's image? Like the one in the DarkSense screenshot?
MaartenXDA said:
Hai So, how could I change the tab's image? Like the one in the DarkSense screenshot?
Click to expand...
Click to collapse
This is not image actually, it is skin support..
I was planning to write about it later ))
OK in manifest after <application tag add this line
allowSkinChange="true"
You will have error. Go to Project and perform a Clean . try and report back
Sent from my Galaxy Nexus using Tapatalk 2
Weird.. Cannot edit ..
So this line should be in the same pack where you have android icon and theme info before the first activity tag
Sent from my Galaxy Nexus using Tapatalk 2
mikrosmile said:
This is not image actually, it is skin support..
I was planning to write about it later ))
OK in manifest after <application tag add this line
allowSkinChange="true"
You will have error. Go to Project and perform a Clean . try and report back
Sent from my Galaxy Nexus using Tapatalk 2
Click to expand...
Click to collapse
Thanks, works great!
Saw the dialog part, nice
Waiting for the listview guide c:
Sent from my awesome fridge
MaartenXDA said:
Saw the dialog part, nice
Waiting for the listview guide c:
Sent from my awesome fridge
Click to expand...
Click to collapse
add an HtcListView it's quite simple!
this works exactly as the android ListView
a simple example:
(as base i've used TabPlus4Demo a sample project in OpenSense SDK samples )
main.xml
HTML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.htc.widget.HtcListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
(Note that you need to use com.htc.widget.HtcListView instead of ListView )
the code:
Code:
public class SimpleTab extends Fragment {
public HtcListView lv;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(getArguments() != null) {
int resId = getArguments().getInt("LAYOUT");
if(resId != 0)
return inflater.inflate(resId, null);
}
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.main, container, false);
[B]//Find the view[/B]
lv = (HtcListView) rootView.findViewById(R.id.listView1);
[B]//create the list[/B]
List<String> list = new ArrayList<String>();
[B]//add some list Items ( if you want a custom text , just use list.add("blahblah")[/B]
for (int i =0; i<40; i++) {
list.add("Test"+i);
}
[B]//create the adapter[/B]
ArrayAdapter<?> adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_1, list);
[B]//Set the adapter[/B]
lv.setAdapter(adapter);
[B]/*
create and set the Listener
you can also implement this in your activity with
"public class youractivity extends Activity implements OnItemClickListener"
then use lv.setOnItemClickListener(this)
*/[/B]
lv.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(HtcAdapterView<?> arg0, View v,
int pos, long id) {
[B]//make a Toast Message that displays the Selected item NAME[/B]
Toast.makeText(v.getContext(),"pressed: "+ lv.getItemAtPosition(pos), Toast.LENGTH_SHORT).show();
[B]/*
if you want t perform something different for each item you can use the case statement
switch(pos){
case 0:
Toast.makeText(v.getContext(), "HI!", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(v.getContext(), "HELLO!", Toast.LENGTH_SHORT).show();
break;
[...]
case 39:
//do something
break;
*/[/B]
}
});
return rootView;
}
}
Result:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
please take a look at this snippet too! ======> LINK
Thanks, good to see you around here
EDIT: and, how could I change it to look like the real HTC listview? I mean with dividers and white background?
Sent from my awesome fridge
MaartenXDA said:
Thanks, good to see you around here
EDIT: and, how could I change it to look like the real HTC listview? I mean with dividers and white background?
Sent from my awesome fridge
Click to expand...
Click to collapse
this is not part of OpenSense SDK.. they wont open it. You need to create own framework..
this is actually part of HtcPreferenceActivity which you cant create in Eclipse without proper libs..
Other than that you can create similar png.9 image and make it looks like )
mikrosmile said:
this is not part of OpenSense SDK.. they wont open it. You need to create own framework..
this is actually part of HtcPreferenceActivity which you cant create in Eclipse without proper libs..
Click to expand...
Click to collapse
Couldn't dex2jar be used on HTCExtension.jar then adding HTCExtension to the build path?
Jonny said:
Couldn't dex2jar be used on HTCExtension.jar then adding HTCExtension to the build path?
Click to expand...
Click to collapse
i didnt try it..
MaartenXDA said:
Thanks, good to see you around here
EDIT: and, how could I change it to look like the real HTC listview? I mean with dividers and white background?
Sent from my awesome fridge
Click to expand...
Click to collapse
i think you can create a custom row layout, create a new custom adapter and set the content with your new adapter
Suggestion for the guide: Htc Preferences

[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!

[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!

swipable menu on left

hI THERE,
How can I in adroid have swipable menu on left..similar to gmail.. ( WHICH when you swipe gives you inbox below it social, promotions, primary then all labels below it starred important chats sent outbox) ..
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
one question.. android.support.v4 does this support honeycomb?
3.0 and above?
krikor1 said:
one question.. android.support.v4 does this support honeycomb?
3.0 and above?
Click to expand...
Click to collapse
http://developer.android.com/reference/android/support/v4/app/package-summary.html
Support android.app classes to assist with development of applications for android API level 4 or later. The main features here are backwards-compatible versions of FragmentManager and LoaderManager.
Click to expand...
Click to collapse
is that what you where asking for?
Implemented it, but what if i want it similar to right one... that is favorites... below it list of buttons..same for others..
http://www.androidhive.info/wp-content/uploads/2013/11/sliding-menu-example-applications.jpg
The implementation purely depends on you. You can inflate multiple list views.
Sent from my Micromax A116
coolbud012 said:
The implementation purely depends on you. You can inflate multiple list views.
Sent from my Micromax A116
Click to expand...
Click to collapse
how do u inflate multiple list views?
Code:
package com.netvariant.alkhaliji;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TabMenu extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList[B], mDrawerList2;[/B]
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems, [B]navDrawerItems2;[/B]
private NavDrawerListAdapter adapter,[B] adapter2;[/B]
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
[B]mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerList2 = (ListView) findViewById(R.id.list_menuslider);[/B]
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
[B]navDrawerItems2.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems2.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));[/B]
// Recycle the typed array
navMenuIcons.recycle();
[B]mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerList2.setOnItemClickListener(new SlideMenuClickListener());[/B]
// setting the nav drawer list adapter
[B]adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems2);
mDrawerList.setAdapter(adapter);
mDrawerList2.setAdapter(adapter2);[/B]
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
[B] // if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
boolean drawerOpen2 = mDrawerLayout.isDrawerOpen(mDrawerList2);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen2);
return super.onPrepareOptionsMenu(menu);[/B]
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
[B]// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerList2.setItemChecked(position, true);
mDrawerList2.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
mDrawerLayout.closeDrawer(mDrawerList2);[/B]
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
modified bolded parts, and i get error
also in xml i added this
Code:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
[B] <ListView
android:id="@+id/list_menuslider"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>[/B]
</android.support.v4.widget.DrawerLayout>
two listviews...instead of one..as i want it subsections...

Dealing with Custom ListView and Fragments

Hi guys! Well, i am facing an issue when trying to develop my app. Let me explain what i have done:
1) Create a Login to connect to a MySQL Database to validate the user (Works great)
2) Create a Main activity
3) Create a Drawer, with a Drawer Adapter, to show the options of my dramer menu. (works great)
As you know the drawer works with fragments, so i have one fragment for each menu option.
4) Well, here starts my problem...
The first option on my menu is "Fixture" where i want to show a list of matchs with the differents results. That list, is on a MySql DB.
So, on my fragment (FixtureFragment) i have this code:
Code:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lxp.app.adapter.FixtureAdapter;
import com.lxp.app.model.FixtureItem;
import com.lxp.app.tools.JSONParser;
import com.lxp.app.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FixtureFragment extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// url to get all products list
private static String url_fixture = "http://www.myweb.com/myFixtureData.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIXUTRE = "fixture";
private static final String TAG_EQUIPO1 = "id_equipo_1";
private static final String TAG_EQUIPO2 = "id_equipo_2";
private static final String TAG_GEQUIPO1 = "goles_equipo_1";
private static final String TAG_GEQUIPO2 = "goles_equipo_2";
private static final String TAG_ID_PARTIDO = "id_partido";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray partidos = null;
ArrayList<HashMap<Integer, FixtureItem>> fixtureList;
ListView lv;
public FixtureFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
/**
* Background Async Task to Load the fixture by making HTTP Request
* */
class LoadFixture extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando el Fixture...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting the Fixture 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_fixture, "GET", params);
// Check your log cat for JSON reponse
Log.d("Fixture: ", json.toString());
FixtureItem objFixture = new FixtureItem();
try {
// Checking for SUCCESS TAG
int success = 0;
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
partidos = json.getJSONArray(TAG_FIXUTRE);
// looping through All Products
for (int i = 0; i < partidos.length(); i++) {
JSONObject c = partidos.getJSONObject(i);
Log.e("Json = ", c.toString());
// Storing each json item in variable
String equipo1 = c.getString(TAG_EQUIPO1);
String equipo2 = c.getString(TAG_EQUIPO2);
String golesEq1 = c.getString(TAG_GEQUIPO1);
String golesEq2 = c.getString(TAG_GEQUIPO2);
Integer idPartido = c.getInt(TAG_ID_PARTIDO);
// creating new HashMap
HashMap<Integer, FixtureItem> map = new HashMap<Integer, FixtureItem>();
// adding each child node to HashMap key => value
objFixture.setGolesEquipo1(golesEq1);
objFixture.setGolesEquipo2(golesEq2);
objFixture.setIdequipo1(equipo1);
objFixture.setIdequipo2(equipo2);
objFixture.setIdPartido(idPartido);
map.put(idPartido, objFixture);
fixtureList.add(map);
}
}
} 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
lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
}
}
}
Well, as you could see, i've created a hashmap to load my fixture data, and then i sent this data (fixtureList) to the custom adapter.
When running this code i am getting this error.
Code:
04-05 16:20:27.899 23500-23500/com.lxp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lxp.app, PID: 23500
java.lang.NullPointerException
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:175)
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:632)
Line 175 --> lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
These are the layouts files:
Fragment_Fixture.xml
Code:
<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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/fixture_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fixture_item.xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/idpartido"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:visibility="gone"/>
<TextView
android:id="@+id/golesequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="0"/>
<TextView
android:id="@+id/golesequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="1"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/idequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Argentinos"/>
<TextView
android:id="@+id/idequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Lanus"/>
</LinearLayout>
</LinearLayout>
My fixtureitem class
Code:
public class FixtureItem {
private Integer idPartido;
private String idequipo1;
private String idequipo2;
private String golesEquipo1;
private String golesEquipo2;
public Integer getIdPartido() {
return idPartido;
}
public void setIdPartido(Integer idPartido) {
this.idPartido = idPartido;
}
public String getIdequipo1() {
return idequipo1;
}
public String getIdequipo2() {
return idequipo2;
}
public String getGolesEquipo1() {
return golesEquipo1;
}
public String getGolesEquipo2() {
return golesEquipo2;
}
public void setIdequipo1(String idequipo1) {
this.idequipo1 = idequipo1;
}
public void setIdequipo2(String idequipo2) {
this.idequipo2 = idequipo2;
}
public void setGolesEquipo1(String golesEquipo1) {
this.golesEquipo1 = golesEquipo1;
}
public void setGolesEquipo2(String golesEquipo2) {
this.golesEquipo2 = golesEquipo2;
}
}
and my fixture adapter
Code:
public class FixtureAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
public FixtureAdapter(Context context, ArrayList listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.fixture_item, null);
holder = new ViewHolder();
holder.idequipo1 = (TextView) convertView.findViewById(R.id.idequipo1);
holder.idequipo2 = (TextView) convertView.findViewById(R.id.idequipo2);
holder.golesequipo1 = (TextView) convertView.findViewById(R.id.golesequipo1);
holder.golesequipo2 = (TextView) convertView.findViewById(R.id.golesequipo2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FixtureItem fixtureItem = (FixtureItem) listData.get(position);
holder.idequipo1.setText(fixtureItem.getGolesEquipo1());
holder.idequipo2.setText(fixtureItem.getGolesEquipo2());
holder.golesequipo1.setText(fixtureItem.getGolesEquipo1());
holder.golesequipo2.setText(fixtureItem.getGolesEquipo1());
return convertView;
}
static class ViewHolder {
TextView idequipo1;
TextView idequipo2;
TextView golesequipo1;
TextView golesequipo2;
}
}
I think i am getting wrong because i couldnt find an example of loading data in an asyncronous way for a list inside a fragment, i know is too expecific this example, but i tried differents ways to do it and i couldnt solve it.
If an experienced dev could give me a hand, i will be glad. Or if you have examples of an app working with "Drawer/Fragment/Custom List inside Fragments/Data Loaded from a MySql for the Custom List" it will be great.
If you need more data, just let me know.
Hey i made two apps with remote mysql database . May be i can help .
Sent from my SM-G900T using Tapatalk
Change
Try changing this:
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
// Loading products in Background Thread
new LoadFixture().execute();
return fixtureView;
}
from
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
Same problem
I have the same problem, not able to solve?
Resolved!!
Missed make reference to listView after inflate places:
lv = (ListView) view.findViewById(R.id.fixture_list);
Click to expand...
Click to collapse
Hugs,
Léo
can anybody help me im trying to display the results in the fragment from customlistview adapter ,there is no error at all but its not also displaying the results..

Categories

Resources