Android 单击 ListViewItem 时加载 fragment

标签 android android-fragments android-listview

我试图在 ListView 中单击 ListView 项时加载 fragment 。 我在滑动选项卡布局中有多个选项卡,每个选项卡都包含一个包含多个项目的 ListView 。 当选项卡更改时,我将固定列表中的第一个项目,以便加载带有控件的相应 fragment 。

现在,当我单击 ListView 时,我正在努力加载第一个 fragment 。

有人可以帮助我实现这一目标吗?

fragment_manual_mode.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/fragment_manual"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/holo_orange_light">

    <Button
        android:id="@+id/f1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="F1" />

    <Button
        android:id="@+id/f2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/f1"
        android:text="F2" />

    <Button
        android:id="@+id/s1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="S1" />

    <Button
        android:id="@+id/s2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/s1"
        android:text="S2" />

    <TextView
        android:id="@+id/text_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/s2"
        android:layout_centerHorizontal="true"
        android:layout_gravity="left|bottom"
        android:text="New Text" />
</RelativeLayout>

选项卡类

package com.grozeaion.www.gvicameraremotecontrol;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by John on 6/12/2015.
 */
public class Tab_Modes extends ListFragment  implements AdapterView.OnItemClickListener {
    private ArrayList<NameImg> items = new ArrayList<NameImg>();
    private int crtMode;
    private FragmentTransaction ft;

    public static final Tab_Modes newInstance(int myInt)
    {
        Tab_Modes f = new Tab_Modes();
        Bundle arguments = new Bundle();
        arguments.putInt("position", myInt);
        f.setArguments(arguments);
        return f;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        crtMode = arguments.getInt("position");
        items.clear();
        ft = getFragmentManager().beginTransaction();
        //Frag2 fragmentObj=(Frag2) geFragmentManager().findFragmentById(R.id.pager);
        //int crtF = findFragmentById(R.id.pager);
         switch (crtMode) {
            case 0:
                items.add(new NameImg("Manual", "Simple camera Control", R.drawable.hand));
                items.add(new NameImg("Bulb", "Long Exposure", R.drawable.bulb));
                items.add(new NameImg("Time Lapse", "Frame by Frame Movie", R.drawable.timelapse));
                items.add(new NameImg("HDR", "High Dinamic Range", R.drawable.hdr));
                items.add(new NameImg("IR", "Infra RED Control", R.drawable.ir));
                //ft.replace(R.id.dummy, ModeManual.newInstance("Manual")).commit();
                break;
            case 1:
                items.add(new NameImg("Triggered", "Trigger camera ", R.drawable.triggrered));
                items.add(new NameImg("Dark Room", "Long Exposure", R.drawable.darkroom));
                items.add(new NameImg("Lightning", "Frame by Frame Movie", R.drawable.lightning));
                //ft.replace(R.id.dummy, ModeTriggered.newInstance("Triggered")).commit();
                break;
            case 2:
                items.add(new NameImg("Bullet", "Simple camera Control", R.drawable.bullet));
                items.add(new NameImg("Water drops", "Long Exposure", R.drawable.waterdrops));
                //ft.replace(R.id.dummy, ModeBullet.newInstance("Bullet")).commit();
                break;
            case 3:
                items.add(new NameImg("Manual", "Simple camera Control", R.drawable.pan_manual));
                items.add(new NameImg("Programmed", "Long Exposure", R.drawable.pan_auto));
                items.add(new NameImg("Star Tracking", "Long Exposure", R.drawable.starstracker));
                //ft.replace(R.id.dummy, ModeManualPan.newInstance("Manual Pan")).commit();
                break;
            case 4:
                items.add(new NameImg("1", "USB1", R.drawable.usb));
                items.add(new NameImg("2", "USB2", R.drawable.waterdrops));
                //ft.replace(R.id.dummy, ModeUSB1.newInstance("USB 1")).commit();
                break;
        }
        setListAdapter(new ModesItemAdapter(getActivity(), R.layout.my_list_item, items));
        Toast.makeText(getActivity(), "onCreate :" + crtMode, Toast.LENGTH_LONG).show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = super.onCreateView(inflater, container, savedInstanceState);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getListView().setOnItemClickListener(this);
        switch (crtMode) {
            case 0:
                ft.add(R.id.dummy, ModeManual.newInstance("Manual")).commit();
                break;
            case 1:
                ft.add(R.id.dummy, ModeTriggered.newInstance("Triggered")).commit();
                break;
            case 2:
                ft.add(R.id.dummy, ModeBullet.newInstance("Bullet")).commit();
                break;
            case 3:
                ft.add(R.id.dummy, ModeManualPan.newInstance("Manual Pan")).commit();
                break;
            case 4:
                ft.add(R.id.dummy, ModeUSB1.newInstance("USB 1")).commit();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getActivity(), "onItemClick :" + parent.getItemAtPosition(0).toString(), Toast.LENGTH_LONG).show();
        //ft = getFragmentManager().beginTransaction();
        //ft.replace(R.id.dummy, ModeManual.newInstance("selected item :" + position + " ID :" + id),"aaa").commit();
    }
}

ModeManual 类

package com.grozeaion.www.gvicameraremotecontrol;

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.TextView;
import android.widget.Toast;


public class ModeManual extends Fragment {
    TextView textDetail;
    private Bundle arguments;
    public static final ModeManual newInstance(String myString)
    {
        ModeManual f = new ModeManual();
        Bundle arguments = new Bundle();
        arguments.putString("myTxt", myString);
        f.setArguments(arguments);
        return f;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        arguments = getArguments();
        View view = inflater.inflate(R.layout.fragment_manual_mode, viewGroup, false);
        textDetail = (TextView) view.findViewById(R.id.text_detail);
        textDetail.setText(arguments.getString("myTxt"));
        return view;
    }
}

activity_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:orientation="vertical"
    tools:context=".MainActivity"
    android:id="@+id/main_activity"
    >

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
         />

    <com.grozeaion.www.gvicameraremotecontrol.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"
        android:layout_below="@+id/tool_bar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_height="match_parent"
        android:layout_width="300dp"
        android:layout_weight="1"
        android:background="#bde354"
        android:layout_below="@+id/tabs">
    </android.support.v4.view.ViewPager>

    <fragment
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:name="com.grozeaion.www.gvicameraremotecontrol.dummy"
        android:id="@+id/dummy"
        tools:layout="@layout/fragment_dummy"
        android:layout_alignTop="@+id/pager"
        android:layout_toRightOf="@+id/pager"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout >

查看寻呼机适配器类

package com.grozeaion.www.gvicameraremotecontrol;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Toast;

/**
 * Created by John on 6/12/2015.
 */
public class ViewPagerAdapter extends FragmentPagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
    private static final int tabIcons[] = {R.drawable.hand, R.drawable.sensors, R.drawable.fastobjects, R.drawable.gears, R.drawable.usb};

    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[]) {
        super(fm);
        this.Titles = mTitles;
        this.NumbOfTabs = mTitles.length;
    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = Tab_Modes.newInstance(position);
        return fragment;
    }

    // This method return the titles for the Tabs in the Tab Strip
    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip
    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}

See image

最佳答案

你在哪里注册了ListView的监听器?

更改为

...extends ListFragment implements OnItemClickListener //class declaration
 getListView().setOnItemClickListener(this) // in onviewcreated/onActivityCreated this is the implemented OnItemClickListener 

 @Override // add this method in the Tab Modes 
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
                 //your code when ListItem is clicked
    }

而不是

myControls = new ModeControls();
            myControls.setArguments(arguments);

Fragment 中使用 newInstance 模式(更好的做法),请参见此处 - https://stackoverflow.com/a/9245510/3325759

关于Android 单击 ListViewItem 时加载 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879747/

相关文章:

javascript - 如何在 Web View 中隐藏 xml 元素后删除空格

android - 在 fragment 中设置焦点

android - 带有 ListView 的上下文操作栏,setselected 不工作

android - 与 TabHost 相比,ViewPager 和 Fragments 的行为不一致

android - 如何在 Android 中制作 Instagram ListView ?

android - 如何在自定义listView上设置CHOICE_MODE_MULTIPLE

android - SIGSEGV memcpy 和 memmove

java - 如何设置 RecyclerView "Android Application"中第一行的背景颜色

android - Android 工具栏的 2 个问题,隐藏的翻译和图标问题

android - 获取 fragment 的容器 View id