How to get text without any button click in android - Java for Android App Development

HEY friends i want help in coding... i want to do simple task.. for eg. "A×25=B" in that task A is edit text number 25 is fix number n B is textview(out put) i want to do this task with out any button... just on edit start at"A" the result shown in "B"... if A change than B is change... sorry m new to coding soooo plz plz plz help me.... which activity or which method i have to follow???

kishnachauhan said:
HEY friends i want help in coding... i want to do simple task.. for eg. "A×25=B" in that task A is edit text number 25 is fix number n B is textview(out put) i want to do this task with out any button... just on edit start at"A" the result shown in "B"... if A change than B is change... sorry m new to coding soooo plz plz plz help me.... which activity or which method i have to follow???
Click to expand...
Click to collapse
Easy I think, I am also a newbie but got this in my mind use this. Create a method.
private addition(){
if(a!=0){
b=a+25;
textview2.settext(b);
}
}
Don't know if its right, just try.

I did this code for you, it works perfectly and there isn't button :good:
Your main activity:
Code:
public class Main extends Activity {
EditText editTextA;
TextView textViewB;
long A, B;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editTextA = (EditText) findViewById(R.id.editText1);
textViewB = (TextView) findViewById(R.id.textView1);
editTextA.addTextChangedListener(new TextWatcher() { // Add listener to EditText
public void afterTextChanged(Editable s) {
if(!editTextA.getText().toString().equals("")) { // If EditText isn't blank
A = Long.parseLong(editTextA.getText().toString()); // Get number of EditText
B = A * 25; // Task
textViewB.setText("" + B); // Set result to TextView
}
else
textViewB.setText("");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
}
Add this in your layout, inside a RelativeLayout (main.xml):
Code:
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:gravity="center" />

Related

[Q] How to create youtube start/stop function for video recording function? HELP!

Is there a way to get the entire surfaceView screen to function like a button which start/atop a video recording process whenever it sees fit by the user? The function is somewhat similar to youTube's start/stop play function but instead this time it is used to start/stop the video recording process.
Is the code suppose to be coded in the .xml file or my .java file to accomplish the task? Sorry i'm rather new to android/java and given only 6 more weeks to finish this assignment by my lecturer to complete an app which act like a car blackbox yet i'm a total beginner in programming... Any help would be appreciated... Thanks in advance...
This is what i tried so far, can someone guide me i'm really in a desperate situation, PLEASE HELP ME :'(
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My serviceRecording.java file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
private boolean RecordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
RecordingStatus = false;
ServiceCamera = CameraTest.MainCamera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (RecordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
RecordingStatus = false;
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
ServiceCamera.unlock();
}
catch(Exception e){
ServiceCamera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(ServiceCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
RecordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
ServiceCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
RecordingStatus = false;
}
}
My .xml file
Code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:text="Video"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></Button>
<Button
android:text="Setting"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
></Button>
<Button
android:text="Back"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
></Button>
<Button
android:text="Start"
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
></Button>
<Button
android:text="Stop"
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
></Button>
<SurfaceView
android:id="@+id/surface_camera"
android:layout_width="480dp"
android:layout_height="320dp"
android:layout_toRightOf="@+id/button2"
></SurfaceView>
<TextView
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/button2"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
></TextView>
<TextView
android:text="TextView"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
></TextView>
</RelativeLayout>
</FrameLayout>
someone answer me please, i really need your guys help...
why isn't someone answering is my question so unwelcoming?
Haiz can anyone help me, i really need some guidance and help here...
You want to
Code:
implement OnClickListener
add method
Code:
onClick(View v)
then you want to add
Code:
surfaceView.setOnClickListener(this);
When surface is clicked onClick is called
By any chance could you explain how should i implement the above said functions into my codes because like implement onclicklistener and this and that i don't quite understand where should i place these above codes??
And how should this above function handle my startService and stopService intents? Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked? Could you guide me in this in much more details, sorry if i'm kinna stupid to understand your explanations...
Ok
CameraTest.java
Add
Code:
public void onClick(View v){
}
Replace
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
with
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback, OnClickListener {
After
Code:
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
Add
Code:
surfaceView.setOnClickListener(this);
how should this above function handle my startService and stopService intents?
Click to expand...
Click to collapse
Your intent function calls the CameraTest.surfaceView so everything will work with whatever code you put in the onClick function.
Will the surfaceview also the show the same invisible button effects seen in youtube too when being clicked?
Click to expand...
Click to collapse
Need better explanation on what you are asking.
The last part is probably like how when you tap a YouTube video on the video itself it kinda flashes the play or pause button over the video.
Sent from my MIUI SCH-i500
Which of these should i import?
Code:
import android.content.DialogInterface.OnClickListener;
import android.view.View.OnClickListener;
Should i put startService and stopService intent together, but it seems not appropriate as both statement seems to conflict each other when i click to start/stop my service? Or i need add some sort of if.. else logic statement to differentiate the start/stop service alternating when being clicked?
Code:
public void onClick(View v){
startService(new Intent(getApplicationContext(), ServiceRecording.class));
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
Yes that was what i meant for the last part of my question the sort of effect it will display when being clicked, sorry if i could not explain well which might cause you some confusion.. Thanks for your help
Or should i be implementing some sort of imagebutton to emulate the above effect i mention or is there some other way to do it?
Can someone answer me??
Can someone please guide me on my above problem to get the result similar to what was like youtube??

[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

buttons action switch between themself

Hi,
i am developing an Android application and i'm facing a curious bug :
a button can randomly take the action of another button.
when i touch a button to open a page, suddenly the menu opens !
I have check all button and their actions (some are configured in the xml layout with the onclick property and others from the Activity with the OnClickListener)
Anyone have an idea to solve the bug ?
Thanks
Yes, read this guide:
http://forum.xda-developers.com/showthread.php?t=2325164
Zatta said:
Yes, read this guide:
http://forum.xda-developers.com/showthread.php?t=2325164
Click to expand...
Click to collapse
Thank you for the link.
No error is logged. It appears to be the normal behavior. But actions are correctly set.
I have never had this problem in any of my apps. If you want to post some of your code. (button definition in your xml and your button click event), they it would be easier to help out.
zalez said:
I have never had this problem in any of my apps. If you want to post some of your code. (button definition in your xml and your button click event), they it would be easier to help out.
Click to expand...
Click to collapse
Menu item button definition :
Code:
<ImageButton
android:id="@+id/menu_button_accueil"
style="@style/fitImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:onClick="onClickMenuItem"
android:src="@drawable/menu_button_accueil" />
<ImageButton
android:id="@+id/menu_button_magasin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:adjustViewBounds="true"
android:background="@null"
android:onClick="onClickMenuItem"
android:scaleType="centerInside"
android:src="@drawable/menu_button_magasin" />
<ImageButton
android:id="@+id/menu_button_carnet_mode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:adjustViewBounds="true"
android:background="@null"
android:onClick="onClickMenuItem"
android:scaleType="centerInside"
android:src="@drawable/menu_button_carnet_mode" />
Menu button toggle definition
Code:
<Button
android:id="@+id/menu_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:background="@drawable/menu_button" />
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
mSlideHolder = (SlideHolder) findViewById(R.id.slideHolder);
mSlideHolder.setDirection(SlideHolder.DIRECTION_RIGHT);
mSlideHolder.setEnabled(false);
menuButton = (Button) findViewById(R.id.menu_button);
menuButton.setOnClickListener(this);
}
[user=439709]@override[/user]
public void onClick(View v) {
Log.d("MainActivity", "toggle menu");
mSlideHolder.toggle();
}
Code:
public void onClickMenuItem(int id) {
Intent i = null;
if(id == currentPage) {
mSlideHolder.toggle();
return;
}
switch(id) {
case R.id.menu_button_accueil:
i = new Intent(MainActivity.this, HomeActivity.class);
break;
case R.id.menu_button_magasin:
i = new Intent(MainActivity.this, MagasinActivity.class);
break;
case R.id.menu_button_carnet_mode:
i = new Intent(MainActivity.this, CarnetModeActivity.class);
break;
case R.id.menu_button_videos:
i = new Intent(MainActivity.this, VideosActivity.class);
break;
case R.id.menu_button_alertes:
i = new Intent(MainActivity.this, AlertesActivity.class);
break;
case R.id.menu_button_aide:
i = new Intent(MainActivity.this, AideActivity.class);
break;
case R.id.menu_button_mentions:
i = new Intent(MainActivity.this, MentionsActivity.class);
break;
default:
Log.d("MainActivity", "not a value in switch");
break;
}
if(i != null) {
MainActivity.currentPage = id;
startActivity(i);
// if(id != R.id.menu_button_accueil)
// finish();
}
else
Log.e("MainActivity", "intent null !!");
}
public void onClickMenuItem(View v) {
this.onClickMenuItem(v.getId());
}

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..

[Q] nullpointer and wrap_content problems

Hello there
I got 2 problems:
Firstly, if I launch the following code on my device, I'm getting a nullpointer, and I got no idea why. ( I know it's sorta basic stuff)
Secondly, I want toset the screen height and lenght to wrap_content, it's red marked in the code...that is also not working..
Could you maybe help out a noob?
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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) {
Random r = new Random();
int x = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
int y = r.nextInt([COLOR="Red"]wrap_content[/COLOR]);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
For the wrap_content one, you need to set that property to the view that holds the integer text, you can't set a height and width properties to an integer, only a view or other widgets such as buttons. So for you you should set the properties of the view with ID start_time to wrap_content for width and height - recommend doing this in the layout XML instead of java code.
I'm guessing that if you sort that out your null pointer will disappear.
Additionally in your public onClick(View v) method you should check the ID of the view before doing any function code, this means you can have multiple objects using the same listener.
So this:
Code:
@Override
public void onClick(View v) {
Random r = new Random();
... etc
Should become this:
Code:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_time:
Random r = new Random();
... etc
tahnks @Jonny for your answer, I changed the code, but now, my button isn't placed randomly on each click anymore, and I'm getting the nullpointer again. have a look:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
/*
sec = (Button) findViewById(R.id.sec);
sec.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long totalTime = SystemClock.elapsedRealtimeNanos()- startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",totalTime);
startActivity(intent);
}
});
*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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) {
Random r = new Random();
int x = r.nextInt(+1);
int y = r.nextInt(+1);
long startTime = SystemClock.elapsedRealtime();
i++;
View b = findViewById(R.id.wrap_content);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the 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"
android:clickable="true"
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.asddd.af.Game" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
thank you. I'm really happy, there exists such great help
i have now changed the view start_time to a button...because it actually IS a button (im stupid) but now, when I click on the button, it moves completely out of the screen, and if not, instead of getting the time, the app stopps again with nullpointer. It should stay in the screen, placed randomly on click and after some clicks, I want to recieve the elapsed time. what is this?
code:
Code:
public class Game extends Activity implements OnClickListener{
Button start_time;
Button sec;
int i = 0;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Random r = new Random();
int x = r.nextInt(R.id.wrap_content);
int y = r.nextInt(R.id.wrap_content);
long startTime = SystemClock.elapsedRealtime();
i++;
Button b = (Button) findViewById(R.id.start_time);
b.setX(x);
b.setY(y);
if (i == 1 ) {
b.setX(+9);
b.setY(+5);
}
if (i == 2 ) {
b.setX(x);
b.setY(y);
}
if (i == 3 ) {
b.setX(x);
b.setY(y);
}
else if (i == 4) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// Toast.makeText(getApplicationContext(), getIntent().getStringExtra("time"), Toast.LENGTH_LONG).show();
textview1.setText(getIntent().getStringExtra("time"));
finish();
}
}
}
and the 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"
android:clickable="true"
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="chdfss.dsfwegg.trhhGame" >
<Button
android:id="@+id/start_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Button" />
<Button
android:id="@+id/sec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start_time"
android:layout_below="@+id/start_time"
android:layout_marginLeft="17dp"
android:layout_marginTop="89dp"
android:text="Button"
android:visibility="gone"/>
<View
android:id="@+id/wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</View>
</RelativeLayout>
I'm not familiar with the nextInt() function (I can look it upp later when I'm home) but I'm pretty sure you shouldn't be parsing a views ID as one of its conditions - eg you're doing nextInt(R.id.wrap_content), are you sure that's right?

Categories

Resources