我创建了一个应用程序,其中有两个片段,并且在两个片段中都有列表视图。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>
有帮助吗?

解决方案

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

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

祝你好运。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top