[Q] Change text in another activity on click. how? - Java for Android App Development
Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visus, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Anser
rodentooth said:
Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
[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.visus, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Click to expand...
Click to collapse
I have Make Fresh Java That will help You
Java
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class JumperPic extends Activity {
Button Nexty;
ImageView Imagey;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jumper);
Nexty = (Button)findViewById(R.id.nextey);
Imagey = (ImageView)findViewById(R.id.imagey);
Nexty.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 2) {
//Your 3 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 3) {
//Your 4 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 10) {
//Image 11 Image
Nexty.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
Layout
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imagey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/avatar_default_1" />
<Button
android:id="@+id/nextey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
In Your Java You can use Button.setOnClickLiestner(new View.OnClickLiestner It will bit easier than it because When We Implement Anything in Your Class we need delcare methods @override somethings you can use int to change Image
In My Java I have int values that will change every click on Button according to values it will change imageview you have write java that is tough from Me you can use my one it will bit easier Ok
Thank you new problem
Thank you so very much AndroidFire withoup you i've wouldn't made it this far. So you say I can use your code (with your name in it) in my Project?
AndroidFire said:
you can use my one it will bit easier Ok
Click to expand...
Click to collapse
Now while this problem is solved another problem has come up.
As I told you in my first thread, there is a finish button. It has this use:
when user clicks next 2 times (so if he made it until the 3rd picture) and then clicks finish, he'll Return to the main activity, and instead of the text 'Klicke auf start um zu beginnen' (click on start to begin) the text 'you made it until the 3rd picture' should show up.
If he clicked Next 5 times (6th picture) and clicks finish, he also returns to the main activity, but the text is 'you made it until the 5th picture'.
And so on with the others.
now i dont know, how to implement multiple buttons, how can I learn that? also how did you learn to code, AndroidFire? It's such a masterpiece *-*
I've tried this, but I failed.
the red lines are those, which I made at my own but they unfortunately don't work
Java Main Activity
Code:
package ch.OptiLab.visustest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.buttonSTART);
btn1.setOnClickListener(this);
[COLOR="red"] Intent intent = getIntent();
if( intent != null)
String inhalt = intent.GetStringExtra("0.1");[/COLOR]
}
@Override
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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(this,VisusActivity.class));
}
}
XML Main Activity
Code:
<RelativeLayout xmlns:android="(external link)"
xmlns:tools="(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.OptiLab.visustest.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/Text1"
android:id="@+id/textView"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center_horizontal"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/Text2"
android:id="@+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:id="@+id/buttonSTART"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="@string/button1"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="142dp" />
</RelativeLayout>
Java 2nd activity
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
[COLOR="red"]finish = (Button)findViewById(R.id.finish);[/COLOR]
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
String content = "You made it until 2nd picture".toString();
i.putExtra("0.1", content);
}
[/COLOR]
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
XML 2nd Activity
Code:
<RelativeLayout xmlns:android="(external link)"
(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.OptiLab.visustest.VisusActivity" >
<ImageView
android:id="@+id/testanzeige"
android:layout_width="231dp"
android:layout_height="231dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/v2" />
<Button
android:id="@+id/next"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="@string/NEXTPIC" />
<Button
android:id="@+id/finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/next"
android:layout_alignBottom="@+id/next"
android:layout_alignParentLeft="true"
android:text="@string/cantread" />
</RelativeLayout>
The most important strings:
Code:
<string name="Text1">Klicke auf Start um zu beginnen.</string>
<string name="cantread">finish</string>
Thank you so much
other way also not work
Well I have tried another solution, but it didn't work either. What do I have to do?
Code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* [user=736105]@author[/user] AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
finish = (Button)findViewById(R.id.finish);
next.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
if (i == 1 ) {
String content = "You got 0.1".toString();
i.putExtra("0.1", content);
[/COLOR]
}
}
}
}
I'm assuming you declared your activity in the Manifest?
F'n noob said:
I'm assuming you declared your activity in the Manifest?
Click to expand...
Click to collapse
uhm I think so.
Edit: there are 2 activity-groups in my manifest, so I think they've been declared automatically?
After looking at your code further, you are using onClick methods but aren't implenting an onClickListener. Are your buttons working at all?
yes, they are working fine. I just dont know how to change the text.
rodentooth said:
yes, they are working fine. I just dont know how to change the text.
Click to expand...
Click to collapse
There are two ways I can think of to solve this one.
The first is to create an Application class, declare that in the manifest, and add a variable in there to save how many images have been seen. Just set it in the one activity and in the other read it, and if it's 0, show the start message, and if it's greater than 0 show the message you want.
The cooler way is to use startActivityForResult to go to the picture viewing activity. The picture viewing activity keeps track of how many the user saw and then, when they leave:
Code:
Intent returnData = new Intent();
returnData.putExtra("PICTURES_SEEN", count);
setResult(RESULT_OK, returnData);
Then, in the first activity:
Code:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
int picturesSeen = data.getExtra("PICTURES_SEEN");
// do stuff
}
}
Hopefully that's helpful.
(There's a page in Google's API called "Getting a Result from an Activity" but I can't link to it because I'm a spammernew.)
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
Text input with DialogFragment
I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a Null pointer exception. My DialogHost class, this constructs, returns and links the parent to its buttons. Code: package jo.app.co; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; public class DialogHost extends DialogFragment { public interface NoticeDialogListener { public void onDialogPositiveClick(DialogFragment dialog); public void onDialogNegativeClick(DialogFragment dialog); } NoticeDialogListener mListener; [user=439709]@override[/user] public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (NoticeDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString()); } } [user=439709]@override[/user] public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); builder.setView(inflater.inflate(R.layout.dialog_add, null)) .setPositiveButton("Save", new DialogInterface.OnClickListener() { [user=439709]@override[/user] public void onClick(DialogInterface dialog, int id) { mListener.onDialogPositiveClick(DialogHost.this); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHost.this.getDialog().cancel(); } }); return builder.create(); } } My MainActivity Code: package jo.app.co; import android.app.DialogFragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.widget.EditText; public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener { [user=439709]@override[/user] protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showNoticeDialog(); } public void showNoticeDialog() { DialogFragment dialog = new DialogHost(); dialog.show(getFragmentManager(), "DialogHost"); } [user=439709]@override[/user] public void onDialogPositiveClick(DialogFragment dialog) { EditText myText = (EditText) findViewById(R.id.item_added); try { Log.d ("IN TRY", myText.getText().toString()); } catch (Exception e) { Log.e ("IN CATCH", e.toString()); } } [user=439709]@override[/user] public void onDialogNegativeClick(DialogFragment dialog) { Log.d ("INMAIN", "REACHED NEG"); } } This is my layout for the add item dialog. Code: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText android:id="@+id/item_added" android:inputType="text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginLeft="4dp" android:layout_marginRight="4dp" android:layout_marginBottom="4dp" android:hint="@string/hint_add_item" /> </LinearLayout>
It's because in your main activity you are trying to call findViewById: swapnilraj said: Code: [user=439709]@override[/user] public void onDialogPositiveClick(DialogFragment dialog) { EditText myText = (EditText) findViewById(R.id.item_added); try { Log.d ("IN TRY", myText.getText().toString()); } catch (Exception e) { Log.e ("IN CATCH", e.toString()); } } Click to expand... Click to collapse This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
SimplicityApks said: It's because in your main activity you are trying to call findViewById: This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead. Click to expand... Click to collapse I tried calling findViewById method in the onClick method in the Dialog class, but the function is not defined for a DialogInterface.onClickListner, I modified it to linearl method you told but I cannot get it to work either. Could you make the changes in the 2 snippets above, it would be very helpful!
You'll have to setup listeners fo this and pass the string or whetever you want to pass to back to the activity which in its turn can handle it (do it by itself or pass this to another fragement). Although not so much votes (0) the last answer here on stackoverflow has exeactly what you need.
text not showing in listview
I am creating a listview with a custom object containing 1 property(i will be creating other activities using objects with more than 1 property). my problem is it shows the correct number of rows but no text. main.xml Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="android link" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ListView android:id="@+id/list" android:layout_height="fill_parent" android:layout_width="fill_parent"/> </LinearLayout> grid_item.xml Code: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="android link" android:layout_width="fill_parent" android:layout_height="fill_parent" android:minHeight="50dp"> <TextView android:id="@+id/item" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:textColor="#FFFFFF" android:text="" android:layout_alignParentLeft="true"/> </RelativeLayout> object java Code: package com.example.sarahjmusicprotocol; import java.io.Console; public class CategoriesObject { String category; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public CategoriesObject() { } public CategoriesObject(String category) { this.category=category; } private void print() { System.out.printf("Category: {0}",category); } [user=439709]@override[/user] public String toString() { return this.getCategory(); } } adapter java Code: package com.example.sarahjmusicprotocol; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.TextView; public class CategoryAdapter extends BaseAdapter { private List<CategoriesObject> categoryList; private LayoutInflater layoutInflater; public CategoryAdapter(final Context context, final List<CategoriesObject> categoriesList) { //super(context,0); this.categoryList = categoriesList; //this.activity=a; layoutInflater = LayoutInflater.from(context); } public CategoriesObject getItem(int position) { return categoryList.get(position); } 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.grid_item, null); holder = new ViewHolder(); holder.titleView=(TextView)convertView.findViewById(R.id.item); convertView.setTag(holder); } else { holder=(ViewHolder)convertView.getTag(); } holder.titleView.setText(categoryList.get(position).getCategory()); return convertView; } public int getCount() { return categoryList.size(); } private static class ViewHolder { public TextView titleView; } } main java Code: package com.example.sarahjmusicprotocol; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; public class Main extends Activity { private ListView view; private CategoryAdapter adapter; private List<CategoriesObject> categoriesList; [user=439709]@override[/user] protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //categoriesList = CategoryDomain.getCategoryDomain().getCategories(); categoriesList = getCategories(); view = (ListView)findViewById(R.id.list); adapter = new CategoryAdapter(this,categoriesList); view.setAdapter(adapter); } private ArrayList getCategories() { ArrayList<CategoriesObject> list = new ArrayList<CategoriesObject>(); list.add(new CategoriesObject("Publishing")); list.add(new CategoriesObject("Publishing")); list.add(new CategoriesObject("Publishing")); list.add(new CategoriesObject("Publishing")); list.add(new CategoriesObject("Publishing")); list.add(new CategoriesObject("Publishing")); return list; } [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; } } any help will be appreciated.
You might want to use a debugger: http://forum.xda-developers.com/showthread.php?t=2325164
nikwen said: You might want to use a debugger: http://forum.xda-developers.com/showthread.php?t=2325164 Click to expand... Click to collapse I'm not getting an error, it just doesn't show the text.
larryse said: I'm not getting an error, it just doesn't show the text. Click to expand... Click to collapse Yeah, have a look at the posts about using the debuggers of Eclipse or AndroidStudio. They help you to understand what your app does. You can see which commands get executed at which time and the you can see the values of variables. That might help you finding the problem. (This doesn't require an Exception.)
Select all children of a group item in ExpandableListView on onItemLongClick
Dears, I have an expandable list view in Android application, I want to achieve the following: When long click on group item, all its children should be selected. vehicle_group_item.xml: Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="""" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:id="@+id/vehicle_group_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="25dp"/> </LinearLayout> vehicle_item.xml: Code: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="""" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" > <TextView android:id="@+id/vehicle_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:paddingLeft="25dp" /> <ImageView android:id="@+id/is_selected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true"/> </RelativeLayout> VehicleListAdapter.java: Code: import java.util.List; import java.util.Map; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.TextView; public class VehicleListAdapter extends BaseExpandableListAdapter { private Activity context; private Map<String, List<String>> vehicleGroupCollection; private List<String> vehicleGroupsList; public VehicleListAdapter(Activity context, List<String> vehicleGroupsList, Map<String, List<String>> vehicleGroupCollection) { this.context = context; this.vehicleGroupsList = vehicleGroupsList; this.vehicleGroupCollection = vehicleGroupCollection; } public Object getChild(int groupPosition, int childPosition) { return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition)).get(childPosition); } public Object getChildren(int groupPosition) { return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition)); } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String vehicle = (String) getChild(groupPosition, childPosition); LayoutInflater inflater = context.getLayoutInflater(); if (convertView == null) { convertView = inflater.inflate(R.layout.vehicle_item, null); } TextView item = (TextView) convertView.findViewById(R.id.vehicle_name); ImageView isSelected = (ImageView) convertView.findViewById(R.id.is_selected); item.setText(vehicle); return convertView; } public int getChildrenCount(int groupPosition) { return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition)).size(); } public Object getGroup(int groupPosition) { return vehicleGroupsList.get(groupPosition); } public int getGroupCount() { return vehicleGroupsList.size(); } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String groupName = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.vehicle_group_item, null); } TextView item = (TextView) convertView.findViewById(R.id.vehicle_group_name); item.setTypeface(null, Typeface.BOLD); item.setText(groupName); return convertView; } public boolean hasStableIds() { return true; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } } In main activity OnCreate method: Code: createGroupList(); createCollection(); MyExpandableList = (ExpandableListView) findViewById(R.id.MyExpandableList); final ExpandableListAdapter expListAdapter = new VehicleListAdapter( this, vehicleGroupList, vehicleGroupCollection); MyExpandableList.setAdapter(expListAdapter); MyExpandableList.setLongClickable(true); MyExpandableList.setOnItemLongClickListener(new OnItemLongClickListener() { [user=439709]@override[/user] public boolean onItemLongClick(AdapterView<?> parent, View v, int groupPosition, long id) { int itemType = ExpandableListView.getPackedPositionType(id); if(itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP){ List<String> mySelectedCollection = (List<String>) ((VehicleListAdapter) expListAdapter).getChildren(groupPosition); if(mySelectedCollection != null){ for (String vehiclepName : mySelectedCollection) { Toast.makeText(getBaseContext(), vehiclepName, Toast.LENGTH_LONG).show(); } return true; } else{ return false; } } return true; } }); The output of the main activity code is Toasting all children text on screen. But, what I want to do, is to set "is_selected" in "ImageView" with Drawable image. After long click on the group item, ALL children of this group get selected. Regards,
Dears, What is wrong with this question? Is it easy question so it does not worth to answer? Or it is tough and no body know the answer? I'm stick with this sine weeks Regards,
[Q]Android Bluetooth - mHandler and manageConnectedSocket errors
Hi! I am beginner in Android programming. I would like to learn how to send a string between 2 devices via Bluetooth. I was trying to write a code on the base of page http://developer.android.com/guide/topics/connectivity/bluetooth.html I got 3 errors. The first one is, that the MainActivity is underlined red in the following row: Code: public class MainActivity extends Activity { It says: 'The blank final field mHandler may not have been initialized' The other 2 errors are shown in the AcceptThread and ConnectThread classes. The following row is underlined red: Code: manageConnectedSocket(socket); It says: 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type AcceptThread' and 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type ConnectThread' Could you please tell me, how to fix the problems and explain me, what were the problems? Thanks in advance. MainActivity.java: Code: package com.example.probax8; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private final static int REQUEST_ENABLE_BT = 1; private BluetoothAdapter mBluetoothAdapter = null; private ArrayAdapter<String> mNewDevicesArrayAdapter; private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); protected static final int MESSAGE_READ = 1; BroadcastReceiver mReceiver; private final Handler mHandler; private BluetoothSocket socket; String address; TextView tv; int a = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //**** Is BlueTooth and enable BT final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth } if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } //**** ON/OFF Bluetooth on click Button btButton = (Button) findViewById(R.id.bBT); btButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(!mBluetoothAdapter.isEnabled()){ mBluetoothAdapter.enable(); } else{ mBluetoothAdapter.disable(); } } }); //**** make Bluetooth discoverable Button discButton = (Button) findViewById(R.id.bDis); discButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); } }); Button stopDiscButton = (Button) findViewById(R.id.bStopDisc); stopDiscButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mBluetoothAdapter.startDiscovery(); } }); Button startDiscButton = (Button) findViewById(R.id.bStartDisc); startDiscButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mBluetoothAdapter.startDiscovery(); } }); tv = (TextView) findViewById(R.id.textView1); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); tv.setText(device.getName() + "\n" + device.getAddress()); } } } }; //**** mNewDevicesArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0); ListView newDevicesListView = (ListView) findViewById(R.id.listView1); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); mNewDevicesArrayAdapter.notifyDataSetChanged(); // newDevicesListView.setOnItemClickListener(mDeviceClickListener); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); newDevicesListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub // mBluetoothAdapter.cancelDiscovery(); final String info = ((TextView) arg1).getText().toString(); //get the device address when click the device item address = info.substring(info.length()-17); a = 1; Log.e(TAG, address); //connect the device when item is click BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address); try { socket = connect_device.createRfcommSocketToServiceRecord(my_UUID); socket.connect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } });//************new_devices_list end if(a==1){ Toast.makeText(this, address,Toast.LENGTH_LONG).show(); } Button unregButton = (Button) findViewById(R.id.bUnreg); unregButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub unregisterReceiver(mReceiver); } }); //************** class AcceptThread extends Thread { private final BluetoothServerSocket mmServerSocket; public AcceptThread() { // Use a temporary object that is later assigned to mmServerSocket, // because mmServerSocket is final BluetoothServerSocket tmp = null; try { // MY_UUID is the app's UUID string, also used by the client code tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("MainActivity", my_UUID); } catch (IOException e) { } mmServerSocket = tmp; } public void run() { BluetoothSocket socket = null; // Keep listening until exception occurs or a socket is returned while (true) { try { socket = mmServerSocket.accept(); } catch (IOException e) { break; } // If a connection was accepted if (socket != null) { // Do work to manage the connection (in a separate thread) manageConnectedSocket(socket); mmServerSocket.close(); } } } /** Will cancel the listening socket, and cause the thread to finish */ public void cancel() { try { mmServerSocket.close(); } catch (IOException e) { } } } //*********** class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket, // because mmSocket is final BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try { // MY_UUID is the app's UUID string, also used by the server code tmp = device.createRfcommSocketToServiceRecord(my_UUID); } catch (IOException e) { } mmSocket = tmp; } public void run() { // Cancel discovery because it will slow down the connection mBluetoothAdapter.cancelDiscovery(); try { // Connect the device through the socket. This will block // until it succeeds or throws an exception mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and get out try { mmSocket.close(); } catch (IOException closeException) { } return; } // Do work to manage the connection (in a separate thread) manageConnectedSocket(mmSocket); } /** Will cancel an in-progress connection, and close the socket */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } //********** class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { break; } } } /* Call this from the main activity to send data to the remote device */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } /* Call this from the main activity to shutdown the connection */ public void cancel() { try { mmSocket.close(); } catch (IOException e) { } } } } } activity_main.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" tools:context="${relativePackage}.${activityClass}" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/bBT" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:text="Bluetooth" /> <Button android:id="@+id/bDis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/bBT" android:text="Disc 300s" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/bDis" > </ListView> <Button android:id="@+id/bRetry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/bBT" android:layout_alignBottom="@+id/bBT" android:layout_toRightOf="@+id/bBT" android:text="Retry" /> <Button android:id="@+id/bUnreg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/bRetry" android:layout_toRightOf="@+id/bRetry" android:text="Unregister" /> <Button android:id="@+id/bStopDisc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/bRetry" android:layout_toRightOf="@+id/bDis" android:text="StopDisc" /> <Button android:id="@+id/bStartDisc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/bUnreg" android:layout_toRightOf="@+id/bStopDisc" android:text="StartDisc" /> </RelativeLayout>