質問

I have a application in which I implement TabActivity, but problem is that after opening the activity when I click back button, the application can't closed,

How can i finish this TabActivity ??

MainActivity.java

package com.productdemo;

import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class MainActivity extends TabActivity {

TabHost tabhost;
TabSpec dashboard, product, customers, order, settings;

public final static int DASHBOARD = 1;
public final static int PRODUCT = 2;
public final static int CUSTOMER = 3;
public final static int ORDER = 4;
public final static int SETTINGS = 5;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tabhost = getTabHost();

    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, TabGroup1Activity.class);
    spec = tabhost.newTabSpec("Dashboard").setIndicator("Dashboard")
            .setContent(intent);
    tabhost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup2Activity.class);
    spec = tabhost.newTabSpec("Product").setIndicator("Product")
            .setContent(intent);
    tabhost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup3Activity.class);
    spec = tabhost.newTabSpec("Customer").setIndicator("Customer")
            .setContent(intent);
    tabhost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup4Activity.class);
    spec = tabhost.newTabSpec("Order").setIndicator("Order")
            .setContent(intent);
    tabhost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup5Activity.class);
    spec = tabhost.newTabSpec("Settings").setIndicator("Settings")
            .setContent(intent);
    tabhost.addTab(spec);

    tabhost.setCurrentTab(1);


    int type = 0;
    if (getIntent().getExtras() != null) {
        if (getIntent().getExtras().containsKey("from")) {
            type = getIntent().getExtras().getInt("from");
            switch (type) {
            case DASHBOARD:
                tabhost.setCurrentTab(0);
            case PRODUCT:
                tabhost.setCurrentTab(1);
            case CUSTOMER:
                tabhost.setCurrentTab(2);
            case ORDER:
                tabhost.setCurrentTab(3);
            case SETTINGS:
                tabhost.setCurrentTab(4);
            default:
                tabhost.setCurrentTab(0);
            }
        }
    }
}

public void switchTabSpecial(int tab) {
    tabhost.setCurrentTab(tab);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private class MyView extends LinearLayout {
    ImageView iv;

    public MyView(Context c, int drawable, int drawableselec, String label) {
        super(c);

        iv = new ImageView(c);
        StateListDrawable listDrawable = new StateListDrawable();
        listDrawable.addState(SELECTED_STATE_SET, this.getResources()
                .getDrawable(drawable));
        listDrawable.addState(ENABLED_STATE_SET, this.getResources()
                .getDrawable(drawableselec));
        iv.setImageDrawable(listDrawable);
        iv.setBackgroundColor(Color.TRANSPARENT);
        iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, (float) 0.0));
        iv.setPadding(0, 0, 0, 5);
        setGravity(Gravity.CENTER);

        addView(iv);
    }
}

@Override
public void onBackPressed() {
    this.finish();
}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="0dp" >
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:padding="0dp" >
    </FrameLayout>
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0" />
    <TabWidget
        android:id="@+id/tabwidget"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0" />
</LinearLayout>

Thanks in advance...

役に立ちましたか?

解決

I just define TabGroupActivity that will manage the child parent relation for Activities,

TabGroup1Activity.java

package com.tabgroupdemo;  

import android.content.Intent;
import android.os.Bundle;

public class TabGroup1Activity extends TabGroupActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startChildActivity("OptionsActivity", new Intent(this, DetailActivity.class));
}
}

DetailActivity.java

package com.tabgroupdemo;

import android.os.Bundle;

public class DetailActivity extends TabGroupActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);

    // write your actual stuff here

}
}

TabGroupActivity.java

package com.tabgroupdemo;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;

/**
 * The purpose of this Activity is to manage the activities in a tab. Note:
 * Child Activities can handle Key Presses before they are seen here.
 * 
 * @author Eric Harlow
 */
public class TabGroupActivity extends ActivityGroup {

private ArrayList<String> mIdList;
String TAG = getClass().getSimpleName();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (mIdList == null)
        mIdList = new ArrayList<String>();
}

/**
 * This is called when a child activity of this one calls its finish method.
 * This implementation calls {@link LocalActivityManager#destroyActivity} on
 * the child activity and starts the previous activity. If the last child
 * activity just called finish(),this activity (the parent), calls finish to
 * finish the entire group.
 */
@Override
public void finishFromChild(Activity child) {

    Log.v(TAG, "finish from child , mIdList size = " + mIdList.size());
    LocalActivityManager manager = getLocalActivityManager();
    int index = mIdList.size() - 1;

    if (index < 1) {
        finish();
        return;
    }
    manager.destroyActivity(mIdList.get(index), true);
    mIdList.remove(index);
    index--;
    String lastId = mIdList.get(index);
    Intent lastIntent = manager.getActivity(lastId).getIntent();
    Window newWindow = manager.startActivity(lastId, lastIntent);
    setContentView(newWindow.getDecorView());
}

/**
 * Starts an Activity as a child Activity to this.
 * 
 * @param Id
 *            Unique identifier of the activity to be started.
 * @param intent
 *            The Intent describing the activity to be started.
 * @throws android.content.ActivityNotFoundException.
 */
public void startChildActivity(String Id, Intent intent) {
    Window window = getLocalActivityManager().startActivity(Id,
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    if (window != null) {
        mIdList.add(Id);
        setContentView(window.getDecorView());
    }
}

/**
 * The primary purpose is to prevent systems before
 * android.os.Build.VERSION_CODES.ECLAIR from calling their default
 * KeyEvent.KEYCODE_BACK during onKeyDown.
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

/**
 * Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
 * all systems call onBackPressed().
 */
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

/**
 * If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
 * add this method.
 */
public void onBackPressed() {
    int length = mIdList.size();
    if (length > 1) {
        Activity current = getLocalActivityManager().getActivity(
                mIdList.get(length - 1));
        current.finish();
    } else {
        finish();
    }
}
}

in TabGroupActivity.java method, the last line is finish() in else part causes the TabActivity to finish.

他のヒント

you can use following code..

intent = new Intent().setClass(this, TabGroup2Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

spec = tabhost.newTabSpec("Product").setIndicator("Product").setContent(intent);

tabhost.addTab(spec);

This code is using in onCreate() method of main activity in every tab intent object...

I'm not sure why the activity won't close, however you shouldn't need

@Override
public void onBackPressed() {
    this.finish();
}

as Android will automatically finish an activity when the back button is pressed.

Try this:

@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
                this.finish();
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top