[单击ListViewItem时的Android加载片段

问题描述 投票:2回答:2

我正在尝试在列表视图中单击列表视图项时加载片段。我在滑动选项卡布局中有几个选项卡,每个选项卡都包含一个包含多个项目的列表视图。当选项卡更改时,我将冻结列表中的第一项,以便加载带有控件的相应片段。

现在,当我单击列表视图时,我正努力仅加载第一个片段。

任何人都可以帮助我实现这一目标吗?

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

android android-fragments android-listview
2个回答
1
投票

您在哪里注册了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);

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


1
投票

谢谢您的帮助。我已经通过使用similar post

我已按照您的建议将假片段替换为框架布局

<FrameLayout
    android:id="@+id/frame_modes"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/tabs"
    android:layout_toEndOf="@+id/pager">
</FrameLayout>

现在,所有人似乎都可以完美地工作。我已经在主要活动中添加了viewPager.addOnPageChangeListener

public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;
    SlidingTabLayout slidingTabLayout;
    CharSequence Titles[] = {"Basic", "Sensors", "Fast Objects", "Pan Tilt", "USB"};
    int Numboftabs = 5;
    FragmentTransaction ft;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Creating The Toolbar and setting it as the Toolbar for the activity
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles for the Tabs and Number Of Tabs.
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles);
        // Assigning ViewPager View and setting the adapter
        viewPager = (ViewPager) findViewById(R.id.pager);
        ft = getSupportFragmentManager().beginTransaction();
        if (savedInstanceState == null) {
            ft.replace(R.id.frame_modes, ModeManual.newInstance("Manual"));
            ft.commit();
        }
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {
            }

            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            public void onPageSelected(int position) {
                ft = getSupportFragmentManager().beginTransaction();
                switch (position) {
                    case 0:
                        ft.replace(R.id.frame_modes, ModeManual.newInstance("Manual"));
                        break;
                    case 1:
                        ft.replace(R.id.frame_modes, ModeTriggered.newInstance("Triggered"));
                        break;
                    case 2:
                        ft.replace(R.id.frame_modes, ModeBullet.newInstance("Bullet"));
                        break;
                    case 3:
                        ft.replace(R.id.frame_modes, ModeManualPan.newInstance("Manual Pan"));
                        break;
                    case 4:
                        ft.replace(R.id.frame_modes, ModeUSB1.newInstance("USB 1"));
                        break;
                }
                ft.commit();
            }
        });
        viewPager.setAdapter(viewPagerAdapter);
        // Assiging the Sliding Tab Layout View
        slidingTabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
        slidingTabLayout.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
        // Setting Custom Color for the Scroll bar indicator of the Tab View
        slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });
        // Setting the ViewPager For the SlidingTabsLayout
        slidingTabLayout.setViewPager(viewPager);
    }

    @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);
    }
}

而且我也使用lv项目上的片段更改单击

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    FragmentTransaction ft= getFragmentManager().beginTransaction();
    switch (position) {
        case 0:
            ft.replace(R.id.frame_modes, ModeManual.newInstance("Manual"));
            break;
        case 1:
            ft.replace(R.id.frame_modes, ModeTriggered.newInstance("Triggered"));
            break;
        case 2:
            ft.replace(R.id.frame_modes, ModeBullet.newInstance("Bullet"));
            break;
        case 3:
            ft.replace(R.id.frame_modes, ModeManualPan.newInstance("Manual Pan"));
            break;
        case 4:
            ft.replace(R.id.frame_modes, ModeUSB1.newInstance("USB 1"));
            break;
    }
    ft.commit();
}

添加其他片段。

再次感谢您的帮助,到目前为止,我在Android上的学习过程非常艰难。但是辛苦的工作现在对我而言已经开始,我需要在I2C,SPI和串行接口上​​连接一些传感器,以使应用程序按需工作。

© www.soinside.com 2019 - 2024. All rights reserved.