I'm working with tabs in android, according to my requirement I need to open a popup containing 5 tabs. That is, I have a Fragment where I have to open a DialogFragment and this DialogFragment need to show my 5 tabs. So far so quiet! Could enter each content on their respective tabs.
But the problem is that when I change the tab, the values that were entered in another tab are clean. example:
I go into tab1 fills any value in a text field and then when I switch to tab2 tab1 back to the value it had before entered is lost.
Given this scenario, how do I retain the values that were filled to the brim change? Follow the code below to explain further.
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;
}
}
File 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>
Try storing those values somewhere e.g.SharedPreferences or static variable and setting them back in onTabChanged().
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 of class
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 of class
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();
}
}
thirdTab of class
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();
}
}
static variable class
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 file
<?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>
put all file and check it
Thanks to all who tried to help me!
I do not have much experience with android but from what I saw, the classes must be executed according to the hierarchy proposed by android. That is, in my case I have a main activity which calls the mine fragments and through one of the fragments I had to call a DialogFragment and this would inflate DialogFragment several Views (my tabs), so I have the following structure:
Activity > Fragment > DialogFragment > Views
Based on this solution for my case was thus:
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;
}
}
Related
I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for fragment_main.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And as last here is my activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!
Fixed it by making a new project with the same code, had to be a problem way deeper than my code.
When I am trying to create tab control and add an edit text in Android, and then enter any character from UI (within Tab1 for Edit Text), the text is not getting entered in the edit text control. I am using Android Studio 1.1.0. Code is as follows.
Main Activity.class
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static final String TAB_1_TAG = "one";
private static final String TAB_2_TAG = "two";
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_tabs);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
Bundle b = new Bundle();
mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Tab1"), FirstContainerFragment.class, b);
b.putString("key", "One");
b = new Bundle();
b.putString("key", "Two");
mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Tab2"), SecondContainerFragment.class, b);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(TAB_1_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
} else if (currentTabTag.equals(TAB_2_TAG)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
}
my_tab.xml
<android.support.v4.app.FragmentTabHost
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
BaseContainerFragment.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
public class BaseContainerFragment extends Fragment {
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.replace(R.id.container_framelayout, fragment);
transaction.commit();
getChildFragmentManager().executePendingTransactions();
}
public boolean popFragment() {
boolean isPop = false;
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getChildFragmentManager().popBackStack();
}
return isPop;
}
}
container_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstContainerFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstContainerFragment extends BaseContainerFragment {
private boolean mIsViewInited;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.container_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!mIsViewInited) {
mIsViewInited = true;
initView();
}
}
private void initView() {
replaceFragment(new FirstFragment(), false);
}
}
FirstFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FirstFragment extends Fragment {
EditText edtTxt;
TextView txtView;
Button btnEnter;
public FirstFragment() {
// TODO Auto-generated constructor stub
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(getActivity()).inflate(R.layout.first_layout,null);
edtTxt =(EditText)v.findViewById(R.id.editText);
txtView =(TextView)v.findViewById(R.id.textText222);
btnEnter = (Button)v.findViewById(R.id.button);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
btnEnter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
txtView.setText(edtTxt.getText());
}
});
}
}
similarly I have the following class and layouts
SecondContainerFragment.java
SecondFragment.java
Nothing much more to say. I'm using a single activity and I go into a Fragment which calls setDisplayHomeAsUpEnabled(Boolean.TRUE) and setHasOptionsMenu(Boolean.TRUE). The menu has two items and the interactions with them are right. I have set breakpoints on all onOptionsItemSelected of the app (which includes the Activity, the Fragment, and the drawer toggle) but when I debug, the menu opens and no breakpoint is triggered.
The Activity and Fragment code in case they help:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:animateLayoutChanges="true">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/content_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/navigation_drawer_fragment"
android:name="org.jorge.lolin1.ui.fragment.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
layout="#layout/fragment_navigation_drawer" />
The Fragment code:
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.TextView;
import com.melnykov.fab.FloatingActionButton;
import com.squareup.picasso.Picasso;
import org.jorge.lolin1.LoLin1Application;
import org.jorge.lolin1.R;
import org.jorge.lolin1.datamodel.FeedArticle;
import org.jorge.lolin1.ui.activity.MainActivity;
import org.jorge.lolin1.ui.util.StickyParallaxNotifyingScrollView;
import org.jorge.lolin1.util.PicassoUtils;
public class ArticleReaderFragment extends Fragment {
private Context mContext;
private int mDefaultImageId;
private String TAG;
private FeedArticle mArticle;
public static final String ARTICLE_KEY = "ARTICLE";
private MainActivity mActivity;
private Drawable mActionBarBackgroundDrawable;
private final Drawable.Callback mDrawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
final ActionBar actionBar = mActivity.getSupportActionBar();
if (actionBar != null)
actionBar.setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
}
};
private ActionBar mActionBar;
private float mOriginalElevation;
private FloatingActionButton mMarkAsReadFab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = LoLin1Application.getInstance().getContext();
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("ArticleReader created without arguments");
mArticle = args.getParcelable(ARTICLE_KEY);
TAG = mArticle.getUrl();
mActivity = (MainActivity) activity;
mDefaultImageId = getArguments().getInt(FeedListFragment.ERROR_RES_ID_KEY);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.actionbar_article_reader, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.homeAsUp:
mActivity.onBackPressed();
return Boolean.TRUE;
case R.id.action_browse_to:
mArticle.requestBrowseToAction(mContext);
return Boolean.TRUE;
case R.id.action_share:
mArticle.requestShareAction(mContext);
return Boolean.TRUE;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(Boolean.TRUE);
final View ret = inflater.inflate(R.layout.fragment_article_reader, container, Boolean.FALSE);
View mHeaderView = ret.findViewById(R.id.image);
PicassoUtils.loadInto(mContext, mArticle.getImageUrl(), mDefaultImageId, (android.widget.ImageView) mHeaderView, TAG);
final String title = mArticle.getTitle();
mHeaderView.setContentDescription(title);
((TextView) ret.findViewById(R.id.title)).setText(title);
((TextView) ret.findViewById(android.R.id.text1)).setText(mArticle.getPreviewText());
mActionBar = mActivity.getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
mActionBarBackgroundDrawable = new ColorDrawable(mContext.getResources().getColor(R.color.toolbar_background));
mActionBar.setBackgroundDrawable(mActionBarBackgroundDrawable);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mOriginalElevation = mActionBar.getElevation();
mActionBar.setElevation(0); //So that the shadow of the ActionBar doesn't show over the article title
}
mActionBar.setTitle(mActivity.getString(R.string.section_title_article_reader));
StickyParallaxNotifyingScrollView scrollView = (StickyParallaxNotifyingScrollView) ret.findViewById(R.id.scroll_view);
scrollView.setOnScrollChangedListener(mOnScrollChangedListener);
scrollView.smoothScrollTo(0, 0);
if (!mArticle.isRead()) {
mMarkAsReadFab = (FloatingActionButton) ret.findViewById(R.id.fab_button_mark_as_read);
mMarkAsReadFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mArticle.markAsRead();
mMarkAsReadFab.hide();
}
});
mMarkAsReadFab.show();
}
return ret;
}
private StickyParallaxNotifyingScrollView.OnScrollChangedListener mOnScrollChangedListener = new StickyParallaxNotifyingScrollView.OnScrollChangedListener() {
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
if (mMarkAsReadFab != null)
if (!who.canScrollVertically(1)) {
mMarkAsReadFab.show();
} else if (t < oldt) {
mMarkAsReadFab.show();
} else if (t > oldt) {
mMarkAsReadFab.hide();
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
Picasso.with(mContext).cancelTag(TAG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mActionBar.setElevation(mOriginalElevation);
}
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (enter) {
return AnimationUtils.loadAnimation(mContext, R.anim.move_in_from_bottom);
} else {
return AnimationUtils.loadAnimation(mContext, R.anim.move_out_to_bottom);
}
}
}
I have opted for making an activity only for that fragment which doesn't include the nav drawer. But obviously this doesn't answer the question, it just gets a relatively similar behavior.
I'm using android 2.3.3. I've created two tab indicators using custom layout, but there is always a black line between them. Below is the result screen.
I want to delete or hide the two black lines. I think those two are tab dividers, so I using
tabHost.getTabWidget().setDividerDrawable(null)
to delete divider, but nothing happens.
Below is my code:
package com.intasect.htfutures.activities;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import com.intasect.core.tab.TabMainActivity;
import com.intasect.htfutures.activities.competitionpk.PkActivityGroup;
import com.intasect.htfutures.activities.home.HomeActivityGroup;
import com.intasect.htfutures.utils.Const;
public class MainActivity extends TabMainActivity {
int currentTabId = 0;
public static TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = getTabHost();
final TabWidget tabwidges = tabHost.getTabWidget();
Intent intent;
// 首页
intent = new Intent(this, HomeActivityGroup.class);
tabHost.addTab(tabHost.newTabSpec(String.valueOf(TAB_ID_HOME))
.setIndicator(createView(TAB_ID_HOME, true)).setContent(intent));
// 业绩PK
intent = new Intent(this, PkActivityGroup.class);
tabHost.addTab(tabHost.newTabSpec(String.valueOf(TAB_ID_PK))
.setIndicator(createView(TAB_ID_PK)).setContent(intent));
// 设置
// intent = new Intent(this, SettingsActivityGroup.class);
// tabHost.addTab(tabHost.newTabSpec(String.valueOf(TAB_ID_SETTINGS))
// .setIndicator(createView(TAB_ID_SETTINGS)).setContent(intent));
/*
* 设置tab监听事件,改变背景颜色
*/
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
currentTabId = tabHost.getCurrentTab();
chooseTab(tabwidges, currentTabId);
}
});
tabHost.setCurrentTab(currentTabId);
Const.initApp();
}
private static final int TAB_ID_HOME = 0;
private static final int TAB_ID_PK = 1;
// private static final int TAB_ID_SETTINGS = 2;
private static final int TOTAL_TAB_COUNT = 2;
private static final int[] IMAGE_IDS = { R.drawable.btn_tab_home,
R.drawable.btn_tab_home_selected, R.drawable.btn_tab_query,
R.drawable.btn_tab_query_selected };
private View createView(int tabId) {
return createView(tabId, false);
}
private View createView(int tabId, boolean choosed) {
ImageButton image = new ImageButton(this);
changeTabImage(image, tabId, choosed);
return image;
}
private void changeTabImage(ImageButton image, int tabId, boolean choosed) {
image.setImageResource(choosed ? IMAGE_IDS[tabId * 2 + 1]
: IMAGE_IDS[tabId * 2]);
image.setBackgroundColor(choosed ? Color.WHITE : getResources().getColor(R.color.tab_item_gray));
}
private void chooseTab(TabWidget tabwidges, int tabId) {
resetAllTabToUnselected(tabwidges);
ImageButton image = (ImageButton) tabwidges.getChildAt(tabId);
changeTabImage(image, tabId, true);
}
private void resetAllTabToUnselected(TabWidget tabwidges) {
for (int i = 0; i < TOTAL_TAB_COUNT; i++) {
ImageButton image = (ImageButton) tabwidges.getChildAt(i);
changeTabImage(image, i, false);
}
}
}
my layout 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="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="66dip" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_margin="0dp"
android:divider="#null"
android:fadingEdge="none"
android:fadingEdgeLength="0dp"
android:padding="0dp"
android:tabStripEnabled="false" />
</TabHost>
I've tried many ways to delete those two lines, but there is no miracle. How can I remove them?
i figured out by myself.i'm really sorry to ask such a stupid question.that black line is not divider,it is on my picture.i delete that line in my picture,every thing goes perfect.
add these lines in xml for Tabhost|TabWidget
android:divider="#null"
android:fadingEdge="none"
android:fadingEdgeLength="0dp"
I am developing an android Application ,In which i am using FragmentTabHost, I am maintaining a container for each tab, But i am getting problem to reload Tabcontent when i reclick on tabs.
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import com.eDeftsoft.FragmentsContainer.AboutContainerFragment;
import com.eDeftsoft.FragmentsContainer.BaseContainerFragment;
import com.eDeftsoft.FragmentsContainer.CityContainerFragment;
import com.eDeftsoft.FragmentsContainer.HomeContainerFragment;
import com.eDeftsoft.FragmentsContainer.PhotosContainerFragment;
import com.eDeftsoft.Utility.CommonDialogues;
public class HomeScreen extends FragmentActivity {
private static final String TAB_1_TAG = "Home";
private static final String TAB_2_TAG = "Photos";
private static final String TAB_3_TAG = "City";
private static final String TAB_4_TAG = "About";
private FragmentTabHost mTabHost;
TabWidget tbwidget;
HomeContainerFragment homeFragment;
PhotosContainerFragment photosFragment;
CityContainerFragment cityFragment;
AboutContainerFragment aboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
initView();
homeFragment = new HomeContainerFragment();
photosFragment = new PhotosContainerFragment();
cityFragment = new CityContainerFragment();
aboutFragment = new AboutContainerFragment();
}
private void initView() {
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(setMyCustomIndicator(this, TAB_1_TAG, "Home"),
HomeContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_2_TAG, "Photos"),
PhotosContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_3_TAG, "City"),
CityContainerFragment.class, null);
mTabHost.addTab(setMyCustomIndicator(this, TAB_4_TAG, "About"),
AboutContainerFragment.class, null);
setTabHostColors();
mTabHost.setCurrentTabByTag("TAB_1_TAG");
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
mTabHost.getTabWidget().setStripEnabled(false);
tbwidget = mTabHost.getTabWidget();
/*I had Also used This But getting error when i reclick on sametabs*/
// mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
//
// #Override
// public void onTabChanged(String tabId) {
// // TODO Auto-generated method stub
// if (tabId.equals(TAB_1_TAG)) {
// pushFragments(TAB_1_TAG, homeFragment);
// } else if (tabId.equals(TAB_2_TAG)) {
// pushFragments(TAB_1_TAG, photosFragment);
//
// } else if (tabId.equals(TAB_3_TAG)) {
// pushFragments(TAB_1_TAG, cityFragment);
// } else {
// pushFragments(TAB_1_TAG, aboutFragment);
// }
//
// }
// });
}
/*
* insert the fragment into the FrameLayout
*/
// public void pushFragments(String tag, Fragment class1) {
//
// FragmentManager manager = getSupportFragmentManager();
// FragmentTransaction ft = manager.beginTransaction();
//
// ft.replace(R.id.realtabcontent, class1);
// ft.commit();
// }
public TabSpec setMyCustomIndicator(Context con, String tag,
String labeltext) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, null, false);
((TextView) tabIndicator.findViewById(R.id.title)).setText(labeltext);
// ((ImageView) tabIndicator.findViewById(R.id.icon))
// .setImageResource(resid);
return spec.setIndicator(tabIndicator);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
FragmentManager fm = getSupportFragmentManager();
if (currentTabTag.equals(TAB_1_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_1_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_1_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_2_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_2_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_2_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_3_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_3_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_3_TAG)).popFragment();
}
else if (currentTabTag.equals(TAB_4_TAG)) {
for (int entry = 0; entry < fm.getBackStackEntryCount(); entry++) {
String ide = fm.getBackStackEntryAt(entry).getName();
Log.i("TAG" + TAB_4_TAG, "Found fragment: " + ide);
}
isPopFragment = ((BaseContainerFragment) getSupportFragmentManager()
.findFragmentByTag(TAB_4_TAG)).popFragment();
}
if (!isPopFragment) {
CommonDialogues.showAlertDialog(HomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
}
}
private void setTabHostColors() {
for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.TRANSPARENT);
final TextView tv = (TextView) mTabHost.getTabWidget()
.getChildAt(i).findViewById(android.R.id.title);
if (tv == null)
continue;
else
tv.setTextSize(12);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mTabHost = null;
}
}
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
Any help will be appreciated. I had gone through some of tutorials and coderepository but couldn`t found solution to my problem.
How Can i reload The content Of First tab when first tab is clicked again.
I had asked a question
When i go in inner fragments of tab1 , like from fragmentA -> Fragment B and From FragmentB -> fragmentC (and finally i am at fragmentC) , When i select Tab1 again i want to reload tabs and FragmentA should Apper.
I searched a lot and come to the conclusion , We can implement OnTabChangeListner and when any tab is clicked again we can reset it.(I was having need to reload tab when it is clicked 2nd time)
<!--Layout for Tabs -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!-- android:background="#drawable/footer" -->
<FrameLayout
android:id="#+id/tabframeLayout"
android:layout_width="fill_parent"
android:layout_height="#dimen/tabframe_height"
android:layout_marginTop="1dp"
android:background="#FBFAFA" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="#dimen/tab_height"
android:background="#F2F0F0" >
</TabWidget>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.abc.Fragments.FragmentA;
import com.abc.Fragments.FragmentA1;
import com.abc.Fragments.FragmentA2;
import com.abc.Fragments.FragmentA3;
import com.abc.Utility.CommonDialogues;
public class MyHomeScreen extends FragmentActivity implements
OnTabChangeListener {
private TabHost tabHost;
private String currentSelectedTab;
private HashMap<String, ArrayList<Fragment>> hMapTabs;
final int TEXT_ID = 100;
final String arrTabLabel[] = { "FragmentA", "FragmentA1", "FragmentA2",
"FragmentA3" };
final static int arrIcons[] = { R.drawable.homee, R.drawable.photoi,
R.drawable.cityi, R.drawable.abouti };
private MyTabView arrTabs[] = new MyTabView[4];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_home_screen);
hMapTabs = new HashMap<String, ArrayList<Fragment>>();
hMapTabs.put(AppConstant.TAB_1_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_2_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_3_TAG, new ArrayList<Fragment>());
hMapTabs.put(AppConstant.TAB_4_TAG, new ArrayList<Fragment>());
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
tabHost.setup();
TabHost.TabSpec spec = tabHost.newTabSpec(AppConstant.TAB_1_TAG);
tabHost.setCurrentTab(0);
arrTabs[0] = new MyTabView(this, 0, arrTabLabel[0]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[0]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_2_TAG);
arrTabs[1] = new MyTabView(this, 1, arrTabLabel[1]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[1]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_3_TAG);
arrTabs[2] = new MyTabView(this, 2, arrTabLabel[2]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[2]);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(AppConstant.TAB_4_TAG);
arrTabs[3] = new MyTabView(this, 3, arrTabLabel[3]);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(android.R.id.tabcontent);
}
});
spec.setIndicator(arrTabs[3]);
tabHost.addTab(spec);
// set background for Selected Tab
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID);
// tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
// iv.setBackgroundResource(R.color.green);
// Listner for Tab 1//
tabHost.getTabWidget().getChildAt(0)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(0)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_1_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.setCurrentTab(0);
}
}
});
/* Listner for Tab 2 */
tabHost.getTabWidget().getChildAt(1)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(1)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_2_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(1);
tabHost.setCurrentTab(1);
}
}
});
/* Listner for Tab 3 */
tabHost.getTabWidget().getChildAt(2)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(2)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_3_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(2);
tabHost.setCurrentTab(2);
}
}
});
/* Listner for Tab 4 */
tabHost.getTabWidget().getChildAt(3)
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (hMapTabs.size() > 0) {
if (tabHost.getTabWidget().getChildAt(3)
.isSelected()) {
if (hMapTabs.get(AppConstant.TAB_4_TAG).size() > 1) {
resetFragment();
}
}
tabHost.getTabWidget().setCurrentTab(3);
tabHost.setCurrentTab(3);
}
}
});
}
/* Method for adding fragment */
public void addFragments(String tabName, Fragment fragment,
boolean animate, boolean add) {
if (add) {
hMapTabs.get(tabName).add(fragment);
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (animate) {
ft.setCustomAnimations(R.animator.slide_in_right,
R.animator.slide_out_left);
}
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
/* Method for remove fragment */
public void removeFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(
hMapTabs.get(currentSelectedTab).size() - 2);
hMapTabs.get(currentSelectedTab).remove(
hMapTabs.get(currentSelectedTab).size() - 1);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
// reset frgment used when clicked on same tab
private void resetFragment() {
Fragment fragment = hMapTabs.get(currentSelectedTab).get(0);
hMapTabs.get(currentSelectedTab).clear();
hMapTabs.get(currentSelectedTab).add(fragment);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.animator.slide_in_left,
R.animator.slide_out_right);
ft.replace(android.R.id.tabcontent, fragment);
ft.commit();
}
#Override
public void onBackPressed() {
if (hMapTabs.get(currentSelectedTab).size() <= 1) {
// super.onBackPressed();
CommonDialogues.showAlertDialog(MyHomeScreen.this,
"Application Will Exit", "Do you Want to Exit");
} else {
removeFragment();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (hMapTabs.get(currentSelectedTab).size() == 0) {
return;
}
hMapTabs.get(currentSelectedTab)
.get(hMapTabs.get(currentSelectedTab).size() - 1)
.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onTabChanged(String tabName) {
// TODO Auto-generated method stub
currentSelectedTab = tabName;
// make iteration for unselected tab and make normal background
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i)
.findViewById(TEXT_ID);
tv.setTextColor(Color.parseColor("#BDBDBD"));
View iv = (View) tabHost.getTabWidget().getChildAt(i);
iv.setBackgroundColor(0x00000000);
}
TextView tv = (TextView) tabHost.getCurrentTabView().findViewById(
TEXT_ID); // for Selected Tab
tv.setTextColor(Color.parseColor("#2882C6"));
View iv = (View) tabHost.getCurrentTabView();
if (hMapTabs.get(tabName).size() == 0) {
if (tabName.equals(AppConstant.TAB_1_TAG)) {
addFragments(tabName, new FragmentA(), false, true);
} else if (tabName.equals(AppConstant.TAB_2_TAG)) {
addFragments(tabName, new FragmentA1(), false, true);
} else if (tabName.equals(AppConstant.TAB_3_TAG)) {
addFragments(tabName, new FragmentA2(), false, true);
} else if (tabName.equals(AppConstant.TAB_4_TAG)) {
addFragments(tabName, new FragmentA3(), false, true);
}
} else {
addFragments(
tabName,
hMapTabs.get(tabName).get(hMapTabs.get(tabName).size() - 1),
false, false);
}
switch (tabHost.getCurrentTab()) {
case 0:
// we can also set background color of tabview
// iv.setBackgroundResource(R.color.green);
break;
case 1:
// iv.setBackgroundResource(R.color.red);
break;
case 2:
// iv.setBackgroundResource(R.color.yellow);
break;
case 3:
// iv.setBackgroundResource(R.color.twitter);
break;
}
}
private class MyTabView extends LinearLayout {
int nIdx = -1;
TextView tv;
public MyTabView(Context c, int drawableIdx, String label) {
super(c);
ImageView iv = new ImageView(c);
nIdx = drawableIdx;
// used for forground icons//
iv.setImageResource(arrIcons[nIdx]);
tv = new TextView(c);
tv.setText(label);
tv.setGravity(Gravity.BOTTOM);
tv.setTextSize(14.0f);
tv.setTypeface(null, Typeface.BOLD);
tv.setId(TEXT_ID);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.9f);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 0.3f);
layout.setMargins(0, 3, 0, 0);
iv.setLayoutParams(layout);
layout.setMargins(0, 3, 0, 2);
tv.setLayoutParams(param);
tv.setTextColor(Color.parseColor("#BDBDBD"));
setOrientation(LinearLayout.VERTICAL);
setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
addView(iv);
addView(tv);
}
}
}
<!--Layout for FragmenA -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TAB 1 FIRST SCREEN"
android:textColor="#color/dark_blue"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="Go to Next Screen" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
</EditText>
</LinearLayout>
code for fragment A ...it is extend By Basefragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstScreen extends BaseFragment implements OnClickListener {
private Button btnNext;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "I am in onCreate", Toast.LENGTH_LONG).show();
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_firstscreen,
container, false);
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
System.out.println("replace");
return view;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
fragmentTabActivity.addFragments(Const.TAB_FIRST,
new SecondScreen(), true, true);
}
}
Code for BaseFragment is
extend this class with all sub fragment which you are going to add on (While adding fragment use myhomescreenActivity(This object) and call add Function in MyHomeScreen ):
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class BaseFragment extends Fragment {
protected MyHomeScreen myhomescreenActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myhomescreenActivity = (MyHomeScreen) this.getActivity();
}
public boolean onBackPressed() {
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
This is the link of repository on Github for further understanding.......
https://github.com/thankimanish/TabUsingFragment
1.You can try moving your code inside the onCreate method to the onResume method so that every time fragment comes to front the code inside the onResume gets executed and reloads the frament.
2.You can also try overriding the onHiddenChanged method of the fragment and reload the fragment as soon as fragment becomes visible