5

我创建了一个应用程序,其中有两个片段,两个片段中都有列表视图。fragment1 中的第一个列表视图正在滚动,并且项目也被突出显示。但是在第二个片段中,列表视图没有滚动,甚至项目也没有突出显示。有人可以告诉我有什么问题吗?这里的事情是我刚刚通过将相同的片段类放入 xml 中的两个片段来检查这一点。要么他们都应该工作,要么两者都不应该,因为一个与另一个没有什么不同。但是为什么会出现这个问题呢?

我的片段类:

public class Fragment1 extends ListFragment{

    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment1,container,false);
    }
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,countries);
        setListAdapter(adapter);
    }

    public void onListItemClick(ListView parent, View v,int position, long id)
    {
        Toast.makeText(getActivity(), "You have selected "+countries[position], Toast.LENGTH_SHORT).show();
    }

}

主.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:name="com.example.listfragmentexample.Fragment1"
        android:id="@+id/fragment1"
        android:layout_weight="0.5"
        android:layout_width="0dp"
        android:layout_height="200dp" />

    <fragment 
        android:name="com.example.listfragmentexample.Fragment1"
        android:id="@+id/fragment2"
        android:layout_weight="0.5"
        android:layout_width="0dp"
        android:layout_height="300dp"/>
</LinearLayout>

片段1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:drawSelectorOnTop="false"/>

</LinearLayout>
4

1 回答 1

3

因此,根据您的代码,您似乎Fragment1 classmain.xml. 我假设您的活动类只包含onCreate()方法中的setContentView() 。由于两个片段都在一个活动上,因此最初可能只有一个视图被突出显示。我刚刚检查了这个,但它工作正常。相反,您可能一直在滚动它。如果您希望第二个列表视图突出显示,恐怕您可能需要单独的 xml 文件(例如片段 1 和片段 2)和片段的单独类,并通过添加以下代码来关注您首先需要的内容。Just drag the listview in the second fragment,

listView1 = (ListView)findViewById(R.id.listView1);
listView1.requestFocus();

祝你好运。

于 2012-10-01T10:38:49.653 回答