我正在尝试创建一个自定义ListView
,但我甚至无法编译它,因为它在早期就给我这个错误:
Error:(25, 63) error: cannot find symbol variable listing
其中"列出"是ListView
布局的xml文件名。
我做错了什么? 这是我的片段代码:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class ListingFragment extends Fragment {
private CustomcursorAdapter mCustomcursorAdapter;
private ListView mListView;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listing, container, false);
//CursorAdapter
mCustomcursorAdapter = new CustomcursorAdapter(view.getContext(), null, 0);
//ListView
mListView = (ListView) view.findViewById(R.id.listing);
mListView.setAdapter(mCustomcursorAdapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
fragment_listing
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
MainActivity和activity_main
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager.findFragmentById(android.R.id.content) == null) {
Listing listing = new Listing();
fragmentManager.beginTransaction().add(android.R.id.content, listing).commit();
}
}
}
activity_main
<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"
tools:context="${relativePackage}.${activityClass}">
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
答案 0 :(得分:0)
在你的fragment_listing.xml中,你应该添加:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@android:color/transparent" >
</ListView>
</RelativeLayout>
它没有编译,因为你在R.java中没有那个id
修改
在您的activty_main xml中添加:
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
然后在您的MainActivity中添加:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment fragment = new Listing();
transaction.replace(R.id.fragmentContainer,fragment);
ft.addToBackStack(null);
ft.commit();