Member 12690464 Ответов: 1

Реализуйте фрагмент tabhost с помощью пользовательского listview


Я пытаюсь реализовать фрагмент tabhost, но не понимаю, в чем здесь проблема при его реализации. Вот код ниже

ListTab.java
public class ListTab extends FragmentActivity {
// Fragment TabHost as mTabHost
private FragmentTabHost mTabHost;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_activity);

    mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup(ListTab.this, getSupportFragmentManager(), android.R.id.tabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Today's Deal"),
        TabFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Upcomming Deal"),
            TabFragment.class, null);

}
}


TabFragment.java

  public class TabFragment extends Fragment  {
   private static final String TAG = "MyActivity";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.tab_fragment, container, false);
    return V;
     } 
 public void onActivityCreated(Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);
 Log.v(TAG, "Initializing sounds...");
 DBHelper dbhelper=new DBHelper(getActivity()); 
 View v = getView();
 final ListView listview=(ListView) v.findViewById(R.id.list);  
  final ArrayList<items> list=new ArrayList<items>();  
  ArrayList<items> itemlist= dbhelper.getAllItem();  
 Log.v("Query Check", "Working");
 for(Items item : itemlist){
 //item.getName();
 Log.v("Get_FragmentName:", item.getName());
 item.getDetail();
 Log.v("Get_FragmentDetail:", item.getDetail());
 item.getPrice();
 Log.v("Get_FragmentPrice:", String.valueOf(item.getPrice()));
 item.getEndDate();
 Log.v("Get_FragmentEndDate:", item.getEndDate());
 item.getStartDate();
 Log.v("Get_FragmentStartDate:", item.getStartDate());
 item.getImage();
 list.add(item);
 ItemAdapter adapter=new ItemAdapter(getActivity(), list);  
 listview.setAdapter(adapter);
 adapter.notifyDataSetChanged();



            } 


       }

tab_activity.xml

 <android.support.v4.app.fragmenttabhost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="350dp" android:layout_height="80dp">

<linearlayout android:orientation="vertical" android:layout_width="350dp" android:layout_height="80dp">

<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"/>


Что я уже пробовал:

я преобразовал активность во фрагмент, но у меня нет большого представления о фрагментах и вложенных фрагментах

Richard MacCutchan

И у нас нет ни малейшего представления о том, в чем может заключаться ваша проблема.

1 Ответов

Рейтинг:
0

wseng

Это, как я реализую вкладке хост (ReminderPage и выполненных задач). Во фрагменте напоминания есть listView. Вы можете посмотреть здесь.

MainActivity1

public class MainActivity1 extends ActionBarActivity implements ActionBar.TabListener{

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = {"Reminder", "Completed Task"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);
//        id=getIntent().getExtras().getString("ID");
        viewPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mAdapter);
        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        for(int i=0; i<2; i++){
            actionBar.addTab(actionBar.newTab().setText(tabs[i]).setTabListener(this));
        }
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg) {
                // TODO Auto-generated method stub
                actionBar.setSelectedNavigationItem(arg);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    public void onTabReselected(ActionBar.Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction arg1) {
        // TODO Auto-generated method stub
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

}


TabsPagerAdapter

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

       if(index==0) {
           Fragment fragment = new ReminderPage();
           return fragment;
       }
        if(index==1)
        {
            Fragment fragment=new CompletedTask();
            return fragment;
        }

        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 2;
    }

}


ReminderPage

public class ReminderPage extends Fragment implements View.OnClickListener {
 
    AllAdapter adapter;
    ArrayList<SearchList> search = new ArrayList<SearchList>();
    ListView listview;
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.reminder_page, container, false);
        final ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        setHasOptionsMenu(true);
        listview = (ListView) rootView.findViewById(R.id.list_todo);
      
        return rootView;
    }


reminder_page

<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:paddingbottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">



    <imageview android:src="@mipmap/to_do" android:layout_margintop="50dp" android:layout_width="130dp" android:layout_height="210dp" android:id="@+id/imageView" android:gravity="center" android:layout_centerhorizontal="true">

    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginbottom="20dp" android:text="No Reminder List" android:textsize="15dp" android:textcolor="@color/btn_login" android:gravity="center" android:id="@+id/NoData" android:layout_centerhorizontal="true" android:layout_below="@+id/imageView">

    <Button
        android:layout_width="250dp"
        android:layout_height="60dp"
        android:text="Add Reminder"
        android:id="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/NoData"/>



    <relativelayout android:layout_width="match_parent" android:layout_height="wrap_content">

        <listview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/list_todo" android:layout_weight="1" android:layout_alignparentleft="true" android:layout_alignparentbottom="true">


AllAdapter


public class AllAdapter extends BaseAdapter {

    Context context;
    private static ArrayList<SearchList> search;
    private LayoutInflater mInflater;
    ListView listview;


    public AllAdapter(Context context, ArrayList<SearchList> searchList, ListView listview) {
        search=searchList;
        this.listview=listview;
        mInflater = LayoutInflater.from(context);
    }
    public int getCount() {
        return search.size();
    }

    public SearchList getItem(int position) {
        return search.get(position);
    }

    public long getItemId(int position) {
        return search.get(position).getID();
    }

    public void removeItem(int position) {
        search.remove(position);
        this.notifyDataSetChanged();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_to_do, null);
            holder= new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.task_title);
            holder.time = (TextView) convertView.findViewById(R.id.time);
            holder.date = (TextView) convertView.findViewById(R.id.date);
            final ToggleButton toggle =(ToggleButton)convertView.findViewById(R.id.donePic);
            toggle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (toggle.isChecked()) {

                        Toast.makeText(v.getContext(), "Clicked Laugh Vote", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(v.getContext(), "Not Clicked Laugh Vote", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            convertView.setTag(holder);
        }
        holder = (ViewHolder) convertView.getTag();
        holder.text.setText(search.get(position).getTitle());
        holder.time.setText(search.get(position).getTime());
        holder.date.setText(search.get(position).getDate());
        return convertView;
    }

    static class ViewHolder {
        TextView text,time,date;
        ToggleButton toggle;

    }
}


Надеюсь, это поможет.