0

我正在使用 android 中的选项卡,根据我的要求,我需要打开一个包含 5 个选项卡的弹出窗口。也就是说,我有一个片段,我必须在其中打开一个 DialogFragment,并且这个 DialogFragment 需要显示我的 5 个选项卡。到目前为止很安静!可以在各自的选项卡上输入每个内容。但问题是,当我更改选项卡时,在另一个选项卡中输入的值是干净的。示例:我进入 tab1 填充文本字段中的任何值,然后当我切换到 tab2 时,tab1 回到输入之前的值丢失。鉴于这种情况,我如何保留填充到边缘变化的值?按照下面的代码进一步解释。

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import br.com.company.R;
import br.com.company.beans.Ordem;
import br.com.company.dispatcher.IDispacher;
import br.com.company.fragment.helper.IFragmentCo;
import br.com.company.bo.IClasseBO;

public class TabsFragment extends DialogFragment implements OnTabChangeListener {

    private static final String TAG = "FragmentTabs";
    public static final String TAB_DADOS_CLIENTE = "dadosCliente";
    public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
    public static final String TAB_SERVICOS = "servico";
    public static final String TAB_MATERIAIS = "material";
    public static final String TAB_OBSERVACAO = "observacao";

    private View mRoot;
    private Button enviar;
    private Button cancelar;
    private Spinner classe;
    private TabHost mTabHost;

    private Ordem ordem;
    private IClasseBO classeBO;
    private IDispacher dispatch;
    private IFragmentCo ifrag;

    private int mCurrentTab;

    public TabsFragment(IFragmentCo ifrag, Ordem ordem) {
        this.ordem = ordem;
        this.ifrag = ifrag;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mRoot = inflater.inflate(R.layout.ordem_encerramento, null);

        enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);

        cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);

        cancelar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                TabsFragment.this.dismiss();
            }
        });

        mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
        setupTabs();
        return mRoot;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);

        mTabHost.setOnTabChangedListener(this);
        mTabHost.setCurrentTab(mCurrentTab);

        mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));

    }

    private void setupTabs() {
        mTabHost.setup(); // importante!

        mTabHost.addTab(newTab(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, R.ordem_encerramento.dados_cliente));
        mTabHost.addTab(newTab(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, R.ordem_encerramento.defeito_falha));
        mTabHost.addTab(newTab(TAB_SERVICOS, R.string.tab_servico, R.ordem_encerramento.servico));
        mTabHost.addTab(newTab(TAB_MATERIAIS, R.string.tab_material, R.ordem_encerramento.material));
        mTabHost.addTab(newTab(TAB_OBSERVACAO, R.string.tab_observacao, R.ordem_encerramento.observacao));
    }

    private View addView(int resource) {
        LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(resource, null);
        return view;
    }

    private TabSpec newTab(String tag, int labelId, int tabContentId) {
        Log.d(TAG, "buildTab(): tag=" + tag);

        View view = LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
        TextView tv = (TextView) view.findViewById(R.id.tabsText);
        tv.setText(labelId); 

        TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(view);
        tabSpec.setContent(tabContentId);
        return tabSpec;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onTabChanged(String tabId) {
        Log.d(TAG, "onTabChanged(): tabId=" + tabId);
        View view = null;
        if (TAB_DADOS_CLIENTE.equals(tabId)) {
            mTabHost.getTabContentView().removeAllViews();
            mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
            mTabHost.setCurrentTab(0);
        } else if (TAB_DEFEITO_FALHA.equals(tabId)) {   
            view = new DefeitoFalhaView().createView(getActivity());
            mTabHost.getTabContentView().addView(view);
            mTabHost.setCurrentTab(1);
        } else if (TAB_SERVICOS.equals(tabId)) {
            mTabHost.getTabContentView().removeAllViews();
            mTabHost.getTabContentView().addView(addView(R.layout.servico));
            mCurrentTab = 2;
        } else if (TAB_MATERIAIS.equals(tabId)) {
            mTabHost.getTabContentView().removeAllViews();
            mTabHost.getTabContentView().addView(addView(R.layout.materiais));
            mCurrentTab = 3;
        } else if (TAB_OBSERVACAO.equals(tabId)) {
            mTabHost.getTabContentView().removeAllViews();
            mTabHost.getTabContentView().addView(addView(R.layout.observacao));
            mCurrentTab = 4;
        }

    }

    public View getmRoot() {
        return mRoot;
    }

}

文件.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/White"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingRight="10dip" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center_vertical"
            android:paddingLeft="10dip"
            android:text="Devolver OS"
            android:textColor="@color/Black" />

        <View
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+ordem_encerramento/cancelar"
            style="@style/ButtonNovo"
            android:layout_marginLeft="10dip"
            android:text="Cancelar" />

        <Button
            android:id="@+ordem_encerramento/enviar"
            style="@style/ButtonNovo"
            android:layout_marginLeft="10dip"
            android:text="Enviar" />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:background="@xml/menu_bg" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="40dip" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="10dip" >

            <TabHost
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@android:id/tabhost"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#EFEFEF" >

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical" >

                    <TabWidget
                        android:id="@android:id/tabs"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" />

                    <FrameLayout
                        android:id="@android:id/tabcontent"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent" >

                        <FrameLayout
                            android:id="@+ordem_encerramento/dados_cliente"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" />

                        <FrameLayout
                            android:id="@+ordem_encerramento/defeito_falha"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" />

                        <FrameLayout
                            android:id="@+ordem_encerramento/servico"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" />

                        <FrameLayout
                            android:id="@+ordem_encerramento/material"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" />

                        <FrameLayout
                            android:id="@+ordem_encerramento/observacao"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" />
                    </FrameLayout>
                </LinearLayout>
            </TabHost>
        </LinearLayout>
    </ScrollView>

</LinearLayout>
4

3 回答 3

1

尝试将这些值存储在某个地方,例如SharedPreferences静态变量,然后将它们重新设置为onTabChanged().

于 2012-11-01T17:38:18.320 回答
1

TabGroupActivity.java

import java.util.ArrayList;
import com.data.DataClass;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
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;

@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) {
    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) {
        // preventing default implementation previous to
        // android.os.Build.VERSION_CODES.ECLAIR
        // onBackPressed();//Added after
        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));
        if (DataClass.isTemp()) {
            overridePendingTransition(R.anim.slide_in_up,
                    R.anim.slide_in_up);
        }
        current.finish();
    }
}
}

MainTab.java

import com.data.DataClass;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
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.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.LinearLayout.LayoutParams;

public class MainTabInfoMe extends TabActivity {
public final static int HOME = 1;
public final static int DIARY = 2;
public final static int PROGRESS = 3;
long transactionID = -1;
public static TabHost tabHost;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mytabs);
    MyView view = null;

    tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, TabGroup1Activity.class);
    view = new MyView(this, R.drawable.home_select, R.drawable.home, "");
    view.setFocusable(true);
    spec = tabHost.newTabSpec("Home").setIndicator(view).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup2Activity.class);
    view = new MyView(this, R.drawable.prof_select, R.drawable.prof, "");
    view.setFocusable(true);
    spec = tabHost.newTabSpec("Diary").setIndicator(view)
            .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, TabGroup3Activity.class);
    view = new MyView(this, R.drawable.bus_select, R.drawable.bus, "");
    view.setFocusable(true);
    spec = tabHost.newTabSpec("progress").setIndicator(view)
            .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);
    tabHost.getTabWidget().getChildAt(0).getLayoutParams().height =    
            LayoutParams.WRAP_CONTENT;
    tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 
            LayoutParams.WRAP_CONTENT;
    tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 
            LayoutParams.WRAP_CONTENT;

    if (MyApplication.getFrom().equals("Home")) {
        tabHost.setCurrentTab(0);
    } else if (MyApplication.getFrom().equals("Diary")) {
        tabHost.setCurrentTab(1);
    } else if (MyApplication.getFrom().equals("progress")) {
        tabHost.setCurrentTab(2);
    }

    int type = 0;
    if (getIntent().getExtras() != null) {
        if (getIntent().getExtras().containsKey("from")) {
            type = getIntent().getExtras().getInt("from");
            switch (type) {
            case HOME:
                tabHost.setCurrentTab(0);
            case DIARY:
                tabHost.setCurrentTab(1);
            case PROGRESS:
                tabHost.setCurrentTab(2);
            default:
                tabHost.setCurrentTab(0);
            }
        }
    }
}

public long getTransactionID() {
    return transactionID;
}

public void setTransactionID(long l) {
    transactionID = l;
}

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

class ChangeTabReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        tabHost = getTabHost();
        tabHost.setCurrentTab(1);
    }
}

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
protected void onPause() {
    super.onPause();
    if( DataClass.isTemp()){
    overridePendingTransition(R.anim.slide_in_up, R.anim.slide_in_up);
    }
}
@Override
protected void onDestroy() {
    super.onDestroy();
    finish();
}
 }

类的FirstTab

     public class TabGroup1Activity extends TabGroupActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    startChildActivity("OptionsActivity", new Intent(this, 
        MainActivity.class));
}
@Override
public void onBackPressed() {
    super.onBackPressed();
     DataClass.setTemp(false);
    finish();
}
}

类的 SecondTab

     public class TabGroup2Activity extends TabGroupActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    startChildActivity("OptionsActivity", new Intent(this, 
        MainActivity.class));
}
@Override
public void onBackPressed() {
    super.onBackPressed();
     DataClass.setTemp(false);
    finish();
}
}

类的第三个选项卡

     public class TabGroup1Activity extends TabGroupActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    startChildActivity("OptionsActivity", new Intent(this, 
        MainActivity.class));
}
@Override
public void onBackPressed() {
    super.onBackPressed();
     DataClass.setTemp(false);
    finish();
}
}

静态变量类

 import android.app.Application;

 public class MyApplication extends Application {

private static String from = "Home";
public static String getFrom() {
    return from;
}

public static void setFrom(String fromPage) {
    from = fromPage;
}
 }

xml文件

  <?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" >
<TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <RelativeLayout android:orientation="vertical"
        android:layout_width="fill_parent"         
              android:layout_height="fill_parent">
        <FrameLayout android:id="@android:id/tabcontent"
            android:layout_width="fill_parent" 
                android:layout_height="wrap_content" />
        <TabWidget android:id="@android:id/tabs"
            android:layout_width="fill_parent" 
                            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" 
                           android:background="@drawable/topbarbck"/>
    </RelativeLayout>
           </TabHost>
               </LinearLayout>

放置所有文件并检查它

于 2012-11-01T17:41:15.707 回答
1

感谢所有试图帮助我的人!我对android没有太多经验,但据我所见,必须根据android提出的层次结构执行类。也就是说,在我的情况下,我有一个调用我的片段的主要活动,并且通过其中一个片段我必须调用 DialogFragment,这会使 DialogFragment 膨胀几个视图(我的选项卡),所以我有以下结构:

活动 > 片段 > DialogFragment > 视图

基于这个解决方案,我的情况是:

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class OrdemEncerramentoFragment extends DialogFragment implements OnTabChangeListener {

    private static final String TAG = "FragmentTabs";
    public static final String TAB_DADOS_CLIENTE = "dadosCliente";
    public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
    public static final String TAB_SERVICOS = "servico";
    public static final String TAB_MATERIAIS = "material";
    public static final String TAB_OBSERVACAO = "observacao";

    private View mRoot;
    private Button enviar;
    private Button cancelar;
    private TabHost mTabHost;

    private Ordem ordem;
    private IClasseBO classeBO;
    private IDispacher dispatch;
    private IFragmentCo ifrag;

    private int mCurrentTab;

    public OrdemEncerramentoFragment(IFragmentCo ifrag, Ordem ordem) {
        this.ordem = ordem;
        this.ifrag = ifrag;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mRoot = inflater.inflate(R.layout.ordem_encerramento, null);

        enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);

        cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);

        cancelar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                OrdemEncerramentoFragment.this.dismiss();
            }
        });

        enviar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                View view = mTabHost.getChildAt(0);
                new DefeitoFalhaView().getDadosDefeitoFalha(view);
            }
        });

        mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);

        setupTabs();
        return mRoot;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);

        mTabHost.setOnTabChangedListener(this);
        mTabHost.setCurrentTab(0);

    }

    private void setupTabs() {
        mTabHost.setup(); // importante!
        mTabHost.addTab(inserirAba(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, new DadosClienteView().createView(getActivity())));
        mTabHost.addTab(inserirAba(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, new DefeitoFalhaView().createView(getActivity())));
        mTabHost.addTab(inserirAba(TAB_SERVICOS, R.string.tab_servico, new ServicoView().createView(getActivity())));
        mTabHost.addTab(inserirAba(TAB_MATERIAIS, R.string.tab_material, new MaterialView().createView(getActivity())));
        mTabHost.addTab(inserirAba(TAB_OBSERVACAO, R.string.tab_observacao, new ObservacaoView().createView(getActivity())));
    }

    private TabSpec inserirAba(String tag, int labelId, final View view) {
        TabHost.TabSpec spec = mTabHost.newTabSpec(tag);

        spec.setContent(new TabHost.TabContentFactory() {
          public View createTabContent(String tag) {
            return(view);
          }
        });
        spec.setIndicator(buildTabIndicator(labelId));
        return spec;
    }

    private View buildTabIndicator(int msg) {
         View indicator=LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
         TextView tv=(TextView)indicator.findViewById(R.id.tabsText);

         tv.setText(msg);

         return(indicator);
     }


    @Override
    public void onTabChanged(String tabId) {
        Log.d(TAG, "onTabChanged(): tabId=" + tabId);
    }

    public View getmRoot() {
        return mRoot;
    }

}  
于 2012-11-05T20:56:26.087 回答