从子活动切换标签 [英] switching tabs from child activity

查看:175
本文介绍了从子活动切换标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有tabActivity这样的(内部OnCreate中):

  TabHost tabHost = getTabHost();
    //收件箱标签
    TabHost.TabSpec inboxSpec = tabHost.newTabSpec(主页);
    inboxSpec.setIndicator(首页,getResources()getDrawable(R.drawable.icon_inbox));
    意图inboxIntent =新意图(这一点,HomeActivity.class);
    inboxSpec.setContent(inboxIntent);    //发件箱标签
    TabHost.TabSpec outboxSpec = tabHost.newTabSpec(RECORDZ);
    outboxSpec.setIndicator(RECORDZ,getResources()getDrawable(R.drawable.icon_outbox));
    意图outboxIntent =新意图(这一点,RecordActivity.class);
    outboxSpec.setContent(outboxIntent);    //标签标签
    TabHost.TabSpec trendSpec = tabHost.newTabSpec(TRENDLIST);
    trendSpec.setIndicator(TRENDLIST,getResources()getDrawable(R.drawable.tt_list));
    意图trendIntent =新意图(这一点,TrendActivity.class);
    trendSpec.setContent(trendIntent);    //配置文件选项卡
    TabHost.TabSpec profileSpec = tabHost.newTabSpec(配置文件);
    profileSpec.setIndicator(PROFILE,getResources()getDrawable(R.drawable.tt_list));
    意图profileIntent =新意图(这一点,TabTab.class);
    profileSpec.setContent(profileIntent);    //添加所有要则tabspec TabHost
    tabHost.addTab(inboxSpec); //添加收件箱标签
    tabHost.addTab(outboxSpec); //添加发件箱标签
    tabHost.addTab(trendSpec); //添加趋势标签
    tabHost.addTab(profileSpec); //添加配置文件选项卡

在RecordActivity我想以编程方式切换标签。我发现很多code,但没有一个人对我的作品。

我RecordActivity.class

 按钮sendServer;
申通快递的ImageButton precord,startRecord用于,playRecord;
的EditText的WriteMessage;公共字符串newCreateFileName;
私人字符串OUTPUTFILE = NULL;
私人MediaRecorder myAudioRecorder;
私人布尔isRunning;公共ProgressDialog pDialog;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_record);    STO precord =(的ImageButton)findViewById(R.id.sto precord);
    startRecord用于=(的ImageButton)findViewById(R.id.startRecord);
    playRecord =(的ImageButton)findViewById(R.id.playRecord);
    sendServer =(按钮)findViewById(R.id.sendServer);
    的WriteMessage =(EditText上)findViewById(R.id.writeMessage);
    newCreateFileName = RandomAlphaNumericString(12);    STO precord.setEnabled(假);
    playRecord.setEnabled(假);
    。OUTPUTFILE = Environment.getExternalStorageDirectory()getAbsolutePath()+/ss\"+newCreateFileName+\".3gp;
    myAudioRecorder =新MediaRecorder();
    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    myAudioRecorder.setAudioEn codeR(MediaRecorder.OutputFormat.AMR_NB);
    myAudioRecorder.setOutputFile(OUTPUTFILE);    sendServer.setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            pDialog =新ProgressDialog(RecordActivity.this);
            pDialog.setMessage(上传,等待一分钟......);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
            新主题(新的Runnable接口(){
                公共无效的run(){
                    UploadFile(newCreateFileName);
                }
            })。开始();
        }
    });
}公共字符串RandomAlphaNumericString(INT大小){
    字符串的字符=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;
    串newRetName =;
    INT长度= chars.length();
    的for(int i = 0; I<大小;我++){
        newRetName + = chars.split()[(INT)(的Math.random()*(长度 - 1))];
    }
    返回newRetName;
}公共无效UploadFile(字符串newCreateFileName){
    尝试{
        //这里设置你的文件路径
        的FileInputStream fstrm =新FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+\"/ss\"+newCreateFileName+\".3gp\");
        字符串newMyFileName = newCreateFileName;
        //设置您的服务器网页的网址(文件标题/描述)
        HttpFileUpload HFU =新HttpFileUpload(http://myownsitess.com.tr/ss/submitrecord.php,2,writeMessage.getText()的toString());
        hfu.Send_Now(fstrm,newMyFileName);
        pDialog.dismiss();
        //((TabActivity)的getParent())getTabHost()setCurrentTab(2)。。
    }赶上(FileNotFoundException异常五){
       // pDialog.dismiss();
    }
}/////////////////////////////
公共无效启动(查看视图){
    尝试{
        isRunning = TRUE;
        startTimer所();
        myAudioRecorder prepare()。
        myAudioRecorder.start();
    }赶上(IllegalStateException异常五){
        // TODO自动生成catch块
        e.printStackTrace();
    }赶上(IOException异常五){
        // TODO自动生成catch块
        e.printStackTrace();
    }
    startRecord.setEnabled(假);
    STO precord.setEnabled(真);
    Toast.makeText(getApplicationContext()开始录音,Toast.LENGTH_LONG).show();}公共无效停止(查看视图){
    myAudioRecorder.stop();
    myAudioRecorder.release();
    myAudioRecorder = NULL;
    STO precord.setEnabled(假);
    playRecord.setEnabled(真);
    Toast.makeText(getApplicationContext(),音频记录成功,
            Toast.LENGTH_LONG).show();
}公共无效播放(查看视图)抛出:IllegalArgumentException - ,
        SecurityException异常,IllegalStateException异常,IOException异常{
    MediaPlayer的M =新的MediaPlayer();
    m.setDataSource(OUTPUTFILE);
    :M prepare();
    m.start();
    playRecord.setEnabled(假);
    startRecord.setEnabled(真);
    Toast.makeText(getApplicationContext(),OUTPUTFILE,Toast.LENGTH_SHORT).show();
}公共无效startTimer所(){
    新主题(新的Runnable接口(){
        @覆盖
        公共无效的run(){
            尝试{
                视频下载(5000);
            }赶上(例外五){
                e.printStackTrace();
            } {最后
                runOnUiThread(新的Runnable(){
                    @覆盖
                    公共无效的run()
                    {
                        doFinish();
                    }
                });
            }
        }
    })。开始();
}私人同步无效doFinish()
{
    如果(isRunning)
    {
        isRunning = FALSE;
        Toast.makeText(getApplicationContext(),你的时间已经过去,Toast.LENGTH_SHORT).show();
        STO precord.performClick();
        //完成();
    }
}

}

我发现这个code:((TabActivity)的getParent())getTabHost()setCurrentTab(2);

您可以在96个recordActivity源线检查,但它不是为我工作。我得到错误,如:

  android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次可以触摸其观点原来的线程。


解决方案

您正在呼叫 setCurrentTab 从一个非UI线程。你需要要么使用处理程序或一些其他的解决方案通过线程之间的 UploadFile 键,主UI线程运行的消息,或拨打<一个href=\"http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)\"相对=nofollow> Activity.runOnUiThread(了java.lang.Runnable) 使主线程做的标签切换。

但是,一个更好的解决方案是使用,而不是试图缠斗螺纹类似AsyncTasks或类似凌空网络库,可以处理做后台工作,然后回呼到你的主线程做工作后回调的工作就是这样,直接。

I have tabActivity like this (inside oncreate) :

    TabHost tabHost = getTabHost();
    // Inbox Tab
    TabHost.TabSpec inboxSpec = tabHost.newTabSpec(HOMEPAGE);
    inboxSpec.setIndicator(HOMEPAGE, getResources().getDrawable(R.drawable.icon_inbox));
    Intent inboxIntent = new Intent(this, HomeActivity.class);
    inboxSpec.setContent(inboxIntent);

    // Outbox Tab
    TabHost.TabSpec outboxSpec = tabHost.newTabSpec(RECORDZ);
    outboxSpec.setIndicator(RECORDZ, getResources().getDrawable(R.drawable.icon_outbox));
    Intent outboxIntent = new Intent(this, RecordActivity.class);
    outboxSpec.setContent(outboxIntent);

    // Tag Tab
    TabHost.TabSpec trendSpec = tabHost.newTabSpec(TRENDLIST);
    trendSpec.setIndicator(TRENDLIST, getResources().getDrawable(R.drawable.tt_list));
    Intent trendIntent = new Intent(this, TrendActivity.class);
    trendSpec.setContent(trendIntent);

    // Profile Tab
    TabHost.TabSpec profileSpec = tabHost.newTabSpec(PROFILE);
    profileSpec.setIndicator(PROFILE, getResources().getDrawable(R.drawable.tt_list));
    Intent profileIntent = new Intent(this, TabTab.class);
    profileSpec.setContent(profileIntent);

    // Adding all TabSpec to TabHost
    tabHost.addTab(inboxSpec); // Adding Inbox tab
    tabHost.addTab(outboxSpec); // Adding Outbox tab
    tabHost.addTab(trendSpec); // Adding Trend tab
    tabHost.addTab(profileSpec); // Adding Profile tab

In the RecordActivity ı want to switch tabs programmatically. I found a lot of code but no one works for me.

my RecordActivity.class

Button sendServer;
ImageButton stopRecord, startRecord, playRecord;
EditText writeMessage;

public String newCreateFileName;
private String outputFile = null;
private MediaRecorder myAudioRecorder;
private boolean isRunning;

public ProgressDialog pDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_record);

    stopRecord = (ImageButton) findViewById(R.id.stopRecord);
    startRecord = (ImageButton) findViewById(R.id.startRecord);
    playRecord = (ImageButton) findViewById(R.id.playRecord);
    sendServer = (Button) findViewById(R.id.sendServer);
    writeMessage = (EditText) findViewById(R.id.writeMessage);
    newCreateFileName = RandomAlphaNumericString(12);

    stopRecord.setEnabled(false);
    playRecord.setEnabled(false);
    outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ss"+newCreateFileName+".3gp";
    myAudioRecorder = new MediaRecorder();
    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    myAudioRecorder.setOutputFile(outputFile);

    sendServer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pDialog = new ProgressDialog(RecordActivity.this);
            pDialog.setMessage("Uploading, Wait a min...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    UploadFile(newCreateFileName);
                }
            }).start();
        }
    });


}

public String RandomAlphaNumericString(int size){
    String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    String newRetName = "";
    int length = chars.length();
    for (int i = 0; i < size; i++){
        newRetName += chars.split("")[ (int) (Math.random() * (length - 1)) ];
    }
    return newRetName;
}

public void UploadFile(String newCreateFileName){
    try {
        // Set your file path here
        FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/ss"+newCreateFileName+".3gp");
        String newMyFileName = newCreateFileName;
        // Set your server page url (and the file title/description)
        HttpFileUpload hfu = new HttpFileUpload("http://myownsitess.com.tr/ss/submitrecord.php", "2", writeMessage.getText().toString());
        hfu.Send_Now(fstrm, newMyFileName);
        pDialog.dismiss();
        // ((TabActivity) getParent()).getTabHost().setCurrentTab(2);
    } catch (FileNotFoundException e) {
       //  pDialog.dismiss();
    }
}

/////////////////////////////
public void start(View view){
    try {
        isRunning = true;
        startTimer();
        myAudioRecorder.prepare();
        myAudioRecorder.start();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    startRecord.setEnabled(false);
    stopRecord.setEnabled(true);
    Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();

}

public void stop(View view){
    myAudioRecorder.stop();
    myAudioRecorder.release();
    myAudioRecorder  = null;
    stopRecord.setEnabled(false);
    playRecord.setEnabled(true);
    Toast.makeText(getApplicationContext(), "Audio recorded successfully",
            Toast.LENGTH_LONG).show();
}

public void play(View view) throws IllegalArgumentException,
        SecurityException, IllegalStateException, IOException{
    MediaPlayer m = new MediaPlayer();
    m.setDataSource(outputFile);
    m.prepare();
    m.start();
    playRecord.setEnabled(false);
    startRecord.setEnabled(true);
    Toast.makeText(getApplicationContext(), outputFile, Toast.LENGTH_SHORT).show();
}

public void startTimer(){
    new Thread (new Runnable() {
        @Override
        public void run() {
            try{
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run()
                    {
                        doFinish();
                    }
                });
            }
        }
    }).start();
}

private synchronized void doFinish()
{
    if (isRunning)
    {
        isRunning = false;
        Toast.makeText(getApplicationContext(), "Your time is over!", Toast.LENGTH_SHORT).show();
        stopRecord.performClick();
        // finish();
    }
}

}

I found this code : ((TabActivity) getParent()).getTabHost().setCurrentTab(2);

you can check in the line of 96 in the recordActivity source, but Its not work for me. I getting error, like this :

  android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view     hierarchy can touch its views.

解决方案

You're calling setCurrentTab from a non-UI thread. You need to either use Handlers or some other solution to pass messages between the thread running UploadFile and the main UI thread, or call Activity.runOnUiThread(java.lang.Runnable) to make the main thread do the tab-switching.

But a better solution is to use something like AsyncTasks or a networking library like Volley that can handle doing background work and then calling back to your main thread to do post-work callback work like this, instead of trying to wrangle the threads directly.

这篇关于从子活动切换标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆