单击ListViewItem时Android加载片段
Posted
技术标签:
【中文标题】单击ListViewItem时Android加载片段【英文标题】:Android Load fragment when ListViewItem is clicked 【发布时间】:2016-02-26 01:45:18 【问题描述】:我正在尝试在列表视图中单击列表视图项时加载片段。 我在滑动选项卡布局中有几个选项卡,每个选项卡都包含一个包含多个项目的列表视图。 当更改选项卡时,列表中的FIRT项xiched in将加载具有控件的相应片段。
现在,当我单击列表视图时,我正在努力加载第一个片段。
谁能帮我实现这个目标?
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_
android:layout_
android:background="@android:color/holo_orange_light">
<Button
android:id="@+id/f1"
android:layout_
android:layout_
android:text="F1" />
<Button
android:id="@+id/f2"
android:layout_
android:layout_
android:layout_alignParentStart="true"
android:layout_below="@+id/f1"
android:text="F2" />
<Button
android:id="@+id/s1"
android:layout_
android:layout_
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="S1" />
<Button
android:id="@+id/s2"
android:layout_
android:layout_
android:layout_alignParentEnd="true"
android:layout_below="@+id/s1"
android:text="S2" />
<TextView
android:id="@+id/text_detail"
android:layout_
android:layout_
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_
android:layout_
android:orientation="vertical"
tools:context=".MainActivity"
android:id="@+id/main_activity"
>
<include
android:id="@+id/tool_bar"
layout="@layout/tool_bar"
android:layout_
android:layout_
/>
<com.grozeaion.www.gvicameraremotecontrol.SlidingTabLayout
android:id="@+id/tabs"
android:layout_
android:layout_
android:elevation="2dp"
android:background="@color/ColorPrimary"
android:layout_below="@+id/tool_bar"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_
android:layout_
android:layout_weight="1"
android:background="#bde354"
android:layout_below="@+id/tabs">
</android.support.v4.view.ViewPager>
<fragment
android:layout_
android:layout_
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
【问题讨论】:
您遇到的错误是什么? 【参考方案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);
在Fragment
中使用newInstance
模式(更好的做法),请参见此处-https://***.com/a/9245510/3325759
【讨论】:
您好,我已按照您的建议添加了列表视图的侦听器,但第二个片段仍未加载到界面中。与片段的创建方式有关,我仍在研究中。 @ION GROZEA 是不是让听众听到了?并且可以添加 R.id.pager 所在的布局吗? 嗨,在我的应用程序中,主要活动有一个 SlidingTabLayout,每个选项卡都包含一个包含不同项目的列表视图,基本上每次用户滑动到新选项卡时,viewpager 都会加载一个新片段 - 请参阅选项卡模式。每次用户单击列表视图项时,我想添加/替换一个包含多个控件的片段,这必须显示在列表视图的左侧。在这里我完全迷失了,我不知道如何添加这个片段。 - 见文章末尾的图片 嗨,我找到了如下解决方案:我在主要活动中创建了一个虚拟片段,并为每个第一个列表视图项创建了几个片段。当用户滑动主要类别时,我试图在屏幕上加载第一个片段。这部分有效,因为在运行时我知道必须替换虚拟片段,但我不知道在几次滚动后该怎么做。另一个问题是,在第一次运行页面适配器调用两次选项卡模式时,基本上我总是会得到对应于第二个 lv 项目 0 的片段,而不是第一个 lv 第一个项目。知道如何解决这个问题吗? @IONGROZEA 我不确定您所面临的问题究竟是什么。但是 1. 你不需要使用感谢您的帮助。我已经通过使用 similar post
解决了我的问题我已按照您的建议将虚拟片段替换为框架布局
<FrameLayout
android:id="@+id/frame_modes"
android:layout_
android:layout_
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 和串行上连接一些传感器,以使应用程序按需要工作。
【讨论】:
以上是关于单击ListViewItem时Android加载片段的主要内容,如果未能解决你的问题,请参考以下文章
C# Wpf 如何使用其中的按钮更改 Listviewitem 的高度?
当 ListView 有 ItemTemplate 时如何处理 ListViewItem 的右键单击?
WPF:防止在 Shift + 箭头上选择 ListViewItem